Skip to content

Fixed Length Array

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

An XDR array is a collection of XDR entities, much like you might see in any programming language. A fixed length array will always be assumed to have the specified count, no matter how many members the array actually has. Every element of the array must be of the identical type.

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: Returns the intended fixed number of array elements. Returning null indicates that this should be treated as a variable length array array instead.
  • 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 TopThree implements XdrArray
{
    public function __construct(protected array $list)
    {
        $this->list = $list;
    }

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

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

    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 fixed length array:

use StageRightLabs\PhpXdr\XDR;

$topThree = new TopThree(['Cryptonomicon', 'The Diamond Age', 'Snow Crash']);
$xdr = XDR::fresh()->write($topThree, XDR::ARRAY_FIXED);

To decode a fixed length array:

$topThree = $xdr->read(XDR::ARRAY_FIXED, TopThree::class);
$topThree->getXdrArray(); // ['Cryptonomicon', 'The Diamond Age', 'Snow Crash']
Clone this wiki locally