From 054909dbc0cd0c02d590ae0ca74e4495874def3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= Date: Mon, 23 Dec 2024 20:53:00 +0100 Subject: [PATCH] Support default-values for ENUMs (#23) --- lib/avro/schema.php | 15 +++++++++++++++ test/SchemaTest.php | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/avro/schema.php b/lib/avro/schema.php index f002f99..89b0de0 100644 --- a/lib/avro/schema.php +++ b/lib/avro/schema.php @@ -1225,6 +1225,19 @@ public function symbol_index($symbol) throw new AvroException(sprintf("Invalid symbol value '%s'", $symbol)); } + /** + * @return mixed the default value of this field + */ + public function default_value() { return $this->extra_attributes[AvroField::DEFAULT_ATTR] ?? null; } + + /** + * @return boolean true if the field has a default and false otherwise + */ + public function has_default_value() { + return array_key_exists(AvroField::DEFAULT_ATTR, $this->extra_attributes) && + $this->extra_attributes[AvroField::DEFAULT_ATTR] !== null; + } + /** * @return mixed */ @@ -1232,6 +1245,8 @@ public function to_avro() { $avro = parent::to_avro(); $avro[AvroSchema::SYMBOLS_ATTR] = $this->symbols; + if ($this->has_default_value()) + $avro[AvroField::DEFAULT_ATTR] = $this->default_value(); return $avro; } } diff --git a/test/SchemaTest.php b/test/SchemaTest.php index 161bf0a..fdd87f9 100644 --- a/test/SchemaTest.php +++ b/test/SchemaTest.php @@ -572,6 +572,29 @@ function test_enum_doc() $this->assertEquals($schema->doc(), "AB is freaky."); } + function test_enum_default() + { + $json = '{"type": "enum", "name": "blood_types", "symbols": ["A", "AB", "B", "O"]}'; + $schema = AvroSchema::parse($json); + + $this->assertEquals(null, $schema->default_value()); + $this->assertEquals(false, $schema->has_default_value()); + + + $json = '{"type": "enum", "name": "blood_types", "default": "AB", "symbols": ["A", "AB", "B", "O"]}'; + $schema = AvroSchema::parse($json); + + $this->assertEquals([ + 'type' => 'enum', + 'name' => 'blood_types', + 'default' => 'AB', + 'symbols' => ["A", "AB", "B", "O"], + ], $schema->to_avro()); + + $this->assertEquals('AB', $schema->default_value()); + $this->assertEquals(true, $schema->has_default_value()); + } + function test_logical_type() { $json = '{ "type": "bytes", "logicalType": "decimal", "precision": 4, "scale": 2 }';