From e4d970cb1aa886ff7213156bca539fa6640d18cd Mon Sep 17 00:00:00 2001 From: Kang Dels Date: Tue, 25 Jun 2019 18:53:43 +0700 Subject: [PATCH 1/2] Fix option value can accept null --- app/Services/Option.php | 8 ++++++-- tests/Unit/Services/SiteOptionTest.php | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/Services/Option.php b/app/Services/Option.php index 00733b6..1fe09ca 100644 --- a/app/Services/Option.php +++ b/app/Services/Option.php @@ -45,12 +45,16 @@ class Option * Set new value for given option key. * * @param string $key The option key. - * @param string $value The option value to be saved. + * @param mixed $value The option value to be saved. * * @return string The option value. */ - public function set($key, string $value) + public function set($key, $value) { + if (is_null($value) || !is_string($value)) { + $value = ''; + } + $option = $this->option->where('key', $key)->first(); if ($option) { diff --git a/tests/Unit/Services/SiteOptionTest.php b/tests/Unit/Services/SiteOptionTest.php index 566e8ff..c2f3ae7 100644 --- a/tests/Unit/Services/SiteOptionTest.php +++ b/tests/Unit/Services/SiteOptionTest.php @@ -22,6 +22,17 @@ class SiteOptionTest extends TestCase } /** @test */ + public function option_value_null_must_be_converted_to_empty_string() + { + Option::set('testing_key', null); + + $this->seeInDatabase('site_options', [ + 'key' => 'testing_key', + 'value' => '', + ]); + } + + /** @test */ public function option_can_be_get() { \DB::table('site_options')->insert([ From ce07511172055a495e3e4cc7a16bc55fb5828608 Mon Sep 17 00:00:00 2001 From: Kang Dels Date: Tue, 25 Jun 2019 19:07:25 +0700 Subject: [PATCH 2/2] Refactor to use nullable typehint --- app/Services/Option.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Services/Option.php b/app/Services/Option.php index 1fe09ca..844d212 100644 --- a/app/Services/Option.php +++ b/app/Services/Option.php @@ -45,13 +45,13 @@ class Option * Set new value for given option key. * * @param string $key The option key. - * @param mixed $value The option value to be saved. + * @param string $value The option value to be saved. * * @return string The option value. */ - public function set($key, $value) + public function set($key, ?string $value) { - if (is_null($value) || !is_string($value)) { + if (is_null($value)) { $value = ''; }