Skip to content

Commit 054909d

Browse files
authored
Support default-values for ENUMs (#23)
1 parent 820c14b commit 054909d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/avro/schema.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1225,13 +1225,28 @@ public function symbol_index($symbol)
12251225
throw new AvroException(sprintf("Invalid symbol value '%s'", $symbol));
12261226
}
12271227

1228+
/**
1229+
* @return mixed the default value of this field
1230+
*/
1231+
public function default_value() { return $this->extra_attributes[AvroField::DEFAULT_ATTR] ?? null; }
1232+
1233+
/**
1234+
* @return boolean true if the field has a default and false otherwise
1235+
*/
1236+
public function has_default_value() {
1237+
return array_key_exists(AvroField::DEFAULT_ATTR, $this->extra_attributes) &&
1238+
$this->extra_attributes[AvroField::DEFAULT_ATTR] !== null;
1239+
}
1240+
12281241
/**
12291242
* @return mixed
12301243
*/
12311244
public function to_avro()
12321245
{
12331246
$avro = parent::to_avro();
12341247
$avro[AvroSchema::SYMBOLS_ATTR] = $this->symbols;
1248+
if ($this->has_default_value())
1249+
$avro[AvroField::DEFAULT_ATTR] = $this->default_value();
12351250
return $avro;
12361251
}
12371252
}

test/SchemaTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,29 @@ function test_enum_doc()
572572
$this->assertEquals($schema->doc(), "AB is freaky.");
573573
}
574574

575+
function test_enum_default()
576+
{
577+
$json = '{"type": "enum", "name": "blood_types", "symbols": ["A", "AB", "B", "O"]}';
578+
$schema = AvroSchema::parse($json);
579+
580+
$this->assertEquals(null, $schema->default_value());
581+
$this->assertEquals(false, $schema->has_default_value());
582+
583+
584+
$json = '{"type": "enum", "name": "blood_types", "default": "AB", "symbols": ["A", "AB", "B", "O"]}';
585+
$schema = AvroSchema::parse($json);
586+
587+
$this->assertEquals([
588+
'type' => 'enum',
589+
'name' => 'blood_types',
590+
'default' => 'AB',
591+
'symbols' => ["A", "AB", "B", "O"],
592+
], $schema->to_avro());
593+
594+
$this->assertEquals('AB', $schema->default_value());
595+
$this->assertEquals(true, $schema->has_default_value());
596+
}
597+
575598
function test_logical_type()
576599
{
577600
$json = '{ "type": "bytes", "logicalType": "decimal", "precision": 4, "scale": 2 }';

0 commit comments

Comments
 (0)