Skip to content

Commit

Permalink
Support default-values for ENUMs (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
CatoTH authored Dec 23, 2024
1 parent 820c14b commit 054909d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/avro/schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -1225,13 +1225,28 @@ 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
*/
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;
}
}
Expand Down
23 changes: 23 additions & 0 deletions test/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 }';
Expand Down

0 comments on commit 054909d

Please sign in to comment.