Skip to content

Commit

Permalink
Merge pull request #14 from flightphp/update-event-fixes
Browse files Browse the repository at this point in the history
Fixes some flawed logic in the events with update/save
  • Loading branch information
n0nag0n authored May 19, 2024
2 parents d099872 + de9e92b commit 94fd5cd
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"ext-pdo_sqlite": "*",
"phpunit/phpunit": "^9.0",
"squizlabs/php_codesniffer": "^3.8",
"rregeer/phpunit-coverage-check": "^0.3.1"
"rregeer/phpunit-coverage-check": "^0.3.1",
"flightphp/runway": "^0.1.0"
},
"autoload": {
"psr-4": {"flight\\": "src/"}
Expand Down
13 changes: 6 additions & 7 deletions src/ActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -470,17 +470,16 @@ public function insert(): ActiveRecord
*/
public function update(): ActiveRecord
{
if (count($this->dirty) === 0) {
return $this->resetQueryData();
}

$this->processEvent([ 'beforeUpdate', 'beforeSave' ], [ $this ]);

$this->processEvent([ 'beforeUpdate', 'beforeSave' ], [ $this ]);

foreach ($this->dirty as $field => $value) {
$this->addCondition($field, '=', $value, ',', 'set');
}

$this->execute($this->eq($this->primaryKey, $this->{$this->primaryKey})->buildSql(['update', 'set', 'where']), $this->params);
// Only update something if there is something to update
if(count($this->dirty) > 0) {
$this->execute($this->eq($this->primaryKey, $this->{$this->primaryKey})->buildSql(['update', 'set', 'where']), $this->params);
}

$this->processEvent([ 'afterUpdate', 'afterSave' ], [ $this ]);

Expand Down
21 changes: 21 additions & 0 deletions tests/ActiveRecordPdoIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,27 @@ protected function afterInsert(self $self)
$this->assertEquals('defaultpassword', $user->password);
}

public function testUpdateEvents()
{
$user = new class (new PDO('sqlite:test.db')) extends User {
protected function beforeUpdate(self $self)
{
$self->password = 'defaultpassword';
}

protected function afterUpdate(self $self)
{
$self->name .= ' after update';
}
};
$user->name = 'Bob';
$user->password = 'bobbytables';
$user->insert();
$user->update();
$this->assertEquals('Bob after update', $user->name);
$this->assertEquals('defaultpassword', $user->password);
}

public function testLimit()
{
$user = new User(new PDO('sqlite:test.db'));
Expand Down

0 comments on commit 94fd5cd

Please sign in to comment.