From de9e92b4678bf78819bfe18019ea8a2c3de7e63e Mon Sep 17 00:00:00 2001 From: n0nag0n Date: Sun, 19 May 2024 14:39:02 -0600 Subject: [PATCH] Fixes some flawed logic in the events with update/save --- composer.json | 3 ++- src/ActiveRecord.php | 13 ++++++------- tests/ActiveRecordPdoIntegrationTest.php | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 5b8ddda..1a9e4dc 100644 --- a/composer.json +++ b/composer.json @@ -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/"} diff --git a/src/ActiveRecord.php b/src/ActiveRecord.php index 35d1e2b..33e2bd7 100644 --- a/src/ActiveRecord.php +++ b/src/ActiveRecord.php @@ -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 ]); diff --git a/tests/ActiveRecordPdoIntegrationTest.php b/tests/ActiveRecordPdoIntegrationTest.php index 398a2bc..ac98a45 100644 --- a/tests/ActiveRecordPdoIntegrationTest.php +++ b/tests/ActiveRecordPdoIntegrationTest.php @@ -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'));