From 036cb9bc1f0c2b13d8c0732045aead9ec26d217c Mon Sep 17 00:00:00 2001 From: Jeroen Noten Date: Sat, 16 Apr 2016 17:37:18 +0200 Subject: [PATCH] Make sure unguarded() does not change unguarded state on exception --- src/Illuminate/Database/Eloquent/Model.php | 10 +++++----- tests/Database/DatabaseEloquentModelTest.php | 12 ++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index b6982c42ed14..037ddfb35ff6 100755 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -2266,11 +2266,11 @@ public static function unguarded(callable $callback) static::unguard(); - $result = $callback(); - - static::reguard(); - - return $result; + try { + return $callback(); + } finally { + static::reguard(); + } } /** diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 3a81f710369b..1e2d71b4a4cf 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -794,6 +794,18 @@ public function testUnguardedCallDoesNotChangeUnguardedState() Model::reguard(); } + public function testUnguardedCallDoesNotChangeUnguardedStateOnException() + { + try { + Model::unguarded(function () { + throw new Exception; + }); + } catch (Exception $e) { + // ignore the exception + } + $this->assertFalse(Model::isUnguarded()); + } + public function testHasOneCreatesProperRelation() { $model = new EloquentModelStub;