Skip to content

Variable Length Array

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

An XDR array is a collection of XDR entities, much like you might see in any programming language. A variable length array does not need to have a previously agreed upon number of elements. Every element of the array must be of the identical type, and the spec limits the total number of elements to be at most 4294967295.

To facilitate the conversion to and from XDR, this package requires that you wrap your array in a class object that implements the StageRightLabs\PhpXdr\Interfaces\XdrArray interface. This interface has five methods:

  • getXdrArray(): array: Return the underlying array that contains the data of interest.
  • static getXdrLength(): ?int: Return null to indicate a variable length array. Returning an element count here will indicate that it is instead a fixed length array.
  • static getXdrType(): string: A string representing the type of data stored in the array. This can either be one of the primitive constants, or the name of a custom class that implements an XDR interface.
  • static getXdrTypeLength(): ?int: If the array data type requires a specified length it can be declared here. Otherwise return null.
  • static newFromXdr(array $arr): static: Return a new instance of the class. The decoded array is passed in as the only parameter.

For example:

use StageRightLabs\PhpXdr\Interfaces\XdrArray;

class Characters implements XdrArray
{
    public function __construct(protected array $list)
    {
        $this->list = $list;
    }

    public function getXdrArray(): array
    {
        return $this->list;
    }

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

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

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

    public static function newFromXdr(array $arr): static
    {
        return new static($arr);
    }
}

To encode a variable length array:

use StageRightLabs\PhpXdr\XDR;

$characters = new Characters(['Hiro Protagonist', 'Y.T.', 'Juanita Marquez', 'NG', 'Raven', 'Da5id Meier']);
$xdr = XDR::fresh()->write($characters, XDR::ARRAY_VARIABLE);

To decode a variable length array:

$characters = $xdr->read(XDR::ARRAY_VARIABLE, Characters::class);
$characters->getXdrArray(); // ['Hiro Protagonist', 'Y.T.', 'Juanita Marquez', 'NG', 'Raven', 'Da5id Meier']