Skip to content

Optional Data

Ryan Durham edited this page Nov 27, 2021 · 3 revisions

An optional data type is a variation on a union. The discriminator is a boolean. When true the structure has some predefined value, when false the value is void. This is useful for times when business logic dictates that a value may either exist or be null.

To define an optional data type, create a class that implements the StageRightLabs\PhpXdr\Interfaces\XdrOptional interface. This interface has five methods:

  • getXdrEvaluation(): bool: The value of the discriminator, either true or false.
  • getXdrValue(): mixed: The value that should be encoded when the discriminator is true.
  • static getXdrValueType(): string: A string that represents the data type of the implied value. This can either be one of the primitive constants, or the name of a custom class that implements an XDR interface.
  • static getXdrValueLength(): ?int: If the value type requires a specified length, return that here. Otherwise return null.
  • static newFromXdr(bool $evaluation, mixed $value): static; Create a new instance of the class from the discriminator and the decoded value.

For example:

use StageRightLabs\PhpXdr\XDR;
use StageRightLabs\PhpXdr\Interfaces\XdrOptional;

class MiddleName implements XdrOptional
{
    public function __construct(public ?string $name)
    {
        $this->name = $name;
    }
    
    public function getXdrEvaluation(): bool
    {
        return !is_null($this->name);
    }

    public function getXdrValue(): mixed
    {
        return $this->name;
    }

    public static function getXdrValueType(): string
    {
        return XDR::STRING;
    }

    public static function getXdrValueLength(): ?int
    {
        return null;
    }

    public static function newFromXdr(bool $evaluation, mixed $value): static
    {
        return new static($evaluation ? $value : null);
    }
}

To encode an optional data type:

use StageRightLabs\PhpXdr\XDR;

$middleName = new MiddleName('Town');
$xdr = XDR::fresh()->write($middleName, XDR::OPTIONAL);

To decode an optional data type:

$middleName = $xdr->read(XDR::OPTIONAL, MiddleName::class);
$middleName->name == 'Town'; // true
Clone this wiki locally