diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index a2c07d34b0..6cc2639f51 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -625,6 +625,11 @@ class Response extends SwooleResponse } } + if (!$data->isSet($key) && !$rule['required']) { // set output key null if data key is not set and required is false + $output[$key] = null; + continue; + } + if ($rule['array']) { if (!is_array($data[$key])) { throw new Exception($key . ' must be an array of type ' . $rule['type']); diff --git a/tests/unit/Utopia/ResponseTest.php b/tests/unit/Utopia/ResponseTest.php index cd111ec22c..452119fafb 100644 --- a/tests/unit/Utopia/ResponseTest.php +++ b/tests/unit/Utopia/ResponseTest.php @@ -55,12 +55,32 @@ class ResponseTest extends TestCase 'integer' => 123, 'boolean' => true, 'hidden' => 'secret', + 'array' => [ + 'string 1', + 'string 2' + ], ]), 'single'); $this->assertArrayHasKey('string', $output); $this->assertArrayHasKey('integer', $output); $this->assertArrayHasKey('boolean', $output); $this->assertArrayNotHasKey('hidden', $output); + $this->assertIsArray($output['array']); + + // test optional array + $output = $this->response->output(new Document([ + 'string' => 'lorem ipsum', + 'integer' => 123, + 'boolean' => true, + 'hidden' => 'secret', + ]), 'single'); + $this->assertArrayHasKey('string', $output); + $this->assertArrayHasKey('integer', $output); + $this->assertArrayHasKey('boolean', $output); + $this->assertArrayNotHasKey('hidden', $output); + $this->assertArrayHasKey('array', $output); + $this->assertNull($output['array']); + } public function testResponseModelRequired(): void diff --git a/tests/unit/Utopia/Single.php b/tests/unit/Utopia/Single.php index 3bd09ef6da..b7f36d10a8 100644 --- a/tests/unit/Utopia/Single.php +++ b/tests/unit/Utopia/Single.php @@ -28,6 +28,11 @@ class Single extends Model 'type' => self::TYPE_STRING, 'default' => 'default', 'required' => true + ]) + ->addRule('array', [ + 'type' => self::TYPE_STRING, + 'required' => false, + 'array' => true, ]); }