public function save($filePath, $messages)
{
if (false === ($fileHandle = @fopen($filePath, 'wb'))) {
throw new Exception('Unable to write file "' . $filePath . '".');
}
if (false === @flock($fileHandle, LOCK_EX)) {
throw new Exception('Unable to lock file "' . $filePath . '" for reading.');
}
// magic
if ($this->useBigEndian) {
$this->writeBytes($fileHandle, pack('c*', 0x95, 0x4, 0x12, 0xde));
// -107
} else {
$this->writeBytes($fileHandle, pack('c*', 0xde, 0x12, 0x4, 0x95));
// -34
}
// revision
$this->writeInteger($fileHandle, 0);
// message count
$messageCount = count($messages);
$this->writeInteger($fileHandle, $messageCount);
// offset of source message table
$offset = 28;
$this->writeInteger($fileHandle, $offset);
$offset += $messageCount * 8;
$this->writeInteger($fileHandle, $offset);
// hashtable size, omitted
$this->writeInteger($fileHandle, 0);
$offset += $messageCount * 8;
$this->writeInteger($fileHandle, $offset);
// length and offsets for source messages
foreach (array_keys($messages) as $id) {
$length = strlen($id);
$this->writeInteger($fileHandle, $length);
$this->writeInteger($fileHandle, $offset);
$offset += $length + 1;
}
// length and offsets for target messages
foreach ($messages as $message) {
$length = strlen($message);
$this->writeInteger($fileHandle, $length);
$this->writeInteger($fileHandle, $offset);
$offset += $length + 1;
}
// source messages
foreach (array_keys($messages) as $id) {
$this->writeString($fileHandle, $id);
}
// target messages
foreach ($messages as $message) {
$this->writeString($fileHandle, $message);
}
@flock($fileHandle, LOCK_UN);
@fclose($fileHandle);
}