Skip to content

Commit 94fd5cd

Browse files
authored
Merge pull request #14 from flightphp/update-event-fixes
Fixes some flawed logic in the events with update/save
2 parents d099872 + de9e92b commit 94fd5cd

File tree

3 files changed

+29
-8
lines changed

3 files changed

+29
-8
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
"ext-pdo_sqlite": "*",
2626
"phpunit/phpunit": "^9.0",
2727
"squizlabs/php_codesniffer": "^3.8",
28-
"rregeer/phpunit-coverage-check": "^0.3.1"
28+
"rregeer/phpunit-coverage-check": "^0.3.1",
29+
"flightphp/runway": "^0.1.0"
2930
},
3031
"autoload": {
3132
"psr-4": {"flight\\": "src/"}

src/ActiveRecord.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -470,17 +470,16 @@ public function insert(): ActiveRecord
470470
*/
471471
public function update(): ActiveRecord
472472
{
473-
if (count($this->dirty) === 0) {
474-
return $this->resetQueryData();
475-
}
476-
477-
$this->processEvent([ 'beforeUpdate', 'beforeSave' ], [ $this ]);
478-
473+
$this->processEvent([ 'beforeUpdate', 'beforeSave' ], [ $this ]);
474+
479475
foreach ($this->dirty as $field => $value) {
480476
$this->addCondition($field, '=', $value, ',', 'set');
481477
}
482478

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

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

tests/ActiveRecordPdoIntegrationTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,27 @@ protected function afterInsert(self $self)
323323
$this->assertEquals('defaultpassword', $user->password);
324324
}
325325

326+
public function testUpdateEvents()
327+
{
328+
$user = new class (new PDO('sqlite:test.db')) extends User {
329+
protected function beforeUpdate(self $self)
330+
{
331+
$self->password = 'defaultpassword';
332+
}
333+
334+
protected function afterUpdate(self $self)
335+
{
336+
$self->name .= ' after update';
337+
}
338+
};
339+
$user->name = 'Bob';
340+
$user->password = 'bobbytables';
341+
$user->insert();
342+
$user->update();
343+
$this->assertEquals('Bob after update', $user->name);
344+
$this->assertEquals('defaultpassword', $user->password);
345+
}
346+
326347
public function testLimit()
327348
{
328349
$user = new User(new PDO('sqlite:test.db'));

0 commit comments

Comments
 (0)