Skip to content

Commit

Permalink
#15 Added update() method to models.
Browse files Browse the repository at this point in the history
  • Loading branch information
amostajo committed Aug 25, 2020
1 parent 4955d13 commit 1984020
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
33 changes: 32 additions & 1 deletion src/Abstracts/DataModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* @author 10 Quality <[email protected]>
* @license MIT
* @package wp-query-builder
* @version 1.0.7
* @version 1.0.12
*/
abstract class DataModel extends Model
{
Expand Down Expand Up @@ -181,6 +181,37 @@ public function delete()
do_action( 'data_model_' . $this->table . '_deleted', $this );
return $deleted;
}
/**
* Updates specific columns of the model (not the whole object like save()).
* @since 1.0.12
*
* @param array $data Data to update.
*
* @return bool
*/
public function update( $data = [] )
{
// If not data, let save() handle this
if ( empty( $data ) || !is_array( $data ) ) {
return $this->save();
}
global $wpdb;
$success = false;
$protected = $this->protected_properties();
if ( $this->{$this->primary_key} ) {
// Update
$success = $wpdb->update( $this->tablename, array_filter( $data, function( $key ) use( $protected ) {
return ! in_array( $key , $protected );
}, ARRAY_FILTER_USE_KEY ), [$this->primary_key => $this->attributes[$this->primary_key]] );
if ( $success ) {
foreach ( $data as $key => $value ) {
$this->$key = $value;
}
do_action( 'data_model_' . $this->table . '_updated', $this );
}
}
return $success;
}
/**
* Deletes where query.
* @since 1.0.0
Expand Down
23 changes: 22 additions & 1 deletion tests/cases/AbstractModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* @author 10 Quality <[email protected]>
* @license MIT
* @package wp-query-builder
* @version 1.0.7
* @version 1.0.12
*/
class AbstractModelTest extends TestCase
{
Expand Down Expand Up @@ -169,4 +169,25 @@ public function testSaveTimestamps()
$this->assertTrue( $created_at && $created_at->format( $date_format ) === $model->created_at );
$this->assertTrue( $updated_at && $updated_at->format( $date_format ) === $model->updated_at );
}
/**
* Test abstract
* @since 1.0.12
* @group abstract
* @group model
* @group update
*/
public function testUpdate()
{
// Preapre
global $wpdb;
$model = new Model( [
'model_id' => 888999,
'name' => 'test',
] );
// Exec
$flag = $model->update( ['name' => 'updated'] );
// Assert
$this->assertTrue( $flag );
$this->assertEquals( 'updated', $model->name );
}
}

0 comments on commit 1984020

Please sign in to comment.