Skip to content

Enumeration

Ryan Durham edited this page Jan 25, 2022 · 3 revisions

An enumeration represents a single instance of a group of predefined values. Each member of the set is assigned an integer value and this numerical value is what we encode into XDR as an XDR integer.

Imagine we have a value that can only be one of three things: rock, paper or scissors. If we assign each possible member an integer value we can then encode that enumeration as an integer. When decoding it we can use the integer to work out which member of the enumeration has been selected.

We can use a PHP class to represent an enumeration by implementing the StageRightLabs\PhpXdr\Interfaces\XdrEnum interface. This interface requires the implementation of three methods:

  • getXdrSelection(): int: Returns the integer value of the selected item.
  • static newFromXdr(int $value): static: A static method that instantiates a new instance of the class. The decoded integer value is provided as the sole parameter.
  • isValidXdrSelection(int $value): bool: A method for verifying that a given integer is a valid enumeration member.

For example:

use StageRightLabs\PhpXdr\Interfaces\XdrEnum;

class RockPaperScissors implements XdrEnum
{
    const ROCK = 1;
    const PAPER = 2;
    const SCISSORS = 3;

    public function __construct(public int $selection)
    {
        $this->selection = $selection;
    }

    public function getXdrSelection(): int
    {
        return $this->selection;
    }

    public static function newFromXdr(int $value): static
    {
        return new static($value); 
    }

    public function isValidXdrSelection(int $value): bool
    {
        return in_array($value, [
            self::ROCK,
            self::PAPER,
            self::SCISSORS,
        ]);
    }

}

To encode the enum as XDR:

use StageRightLabs\PhpXdr\XDR;

$rps = new RockPaperScissors(RockPaperScissors::PAPER);
$xdr = XDR::fresh()->write($rps, XDR::ENUM);

To decode an XDR enum:

$rds = $xdr->read(XDR::ENUM, RockPaperScissors::class);
$xdr->selection == RockPaperScissors::PAPER; // true

NB: PHP 8.1 introduces enumerations as a first class data type. Enumerations are able to implement interfaces which means you can encode them as XDR using this method.

Clone this wiki locally