public function encode()
{
$this->payloadLength = strlen($this->payloadData);
$firstByte = $this->opcode;
$firstByte += $this->FIN * 128 + $this->RSV1 * 64 + $this->RSV2 * 32 + $this->RSV3 * 16;
$encoded = chr($firstByte);
if ($this->payloadLength <= 125) {
$secondByte = $this->payloadLength;
$secondByte += $this->mask * 128;
$encoded .= chr($secondByte);
} else {
if ($this->payloadLength <= 256 * 256 - 1) {
$secondByte = 126;
$secondByte += $this->mask * 128;
$encoded .= chr($secondByte) . pack("n", $this->payloadLength);
} else {
// TODO: max length is now 32 bits instead of 64 !!!!!
$secondByte = 127;
$secondByte += $this->mask * 128;
$encoded .= chr($secondByte);
$encoded .= pack("N", 0);
$encoded .= pack("N", $this->payloadLength);
}
}
$key = 0;
if ($this->mask) {
$key = pack("N", rand(0, PHP_INT_MAX));
$encoded .= $key;
}
if ($this->payloadData) {
$encoded .= $this->mask == 1 ? $this->rotMask($this->payloadData, $key) : $this->payloadData;
}
return $encoded;
}