/** * Writes a variable to an actual file on the FS * If the variable was already loaded from a file, it will be used and overwritten, * except if a specific directory and name are provided. * * @param string $directory Directory to save the file to * @param string $name Name of the file, without the extension * * @throws \Exception (if output file can't be written to) */ public function saveVarToFile($directory = '', $name = '') { $fullPath = ''; if ($this->isFromFile && $directory === '') { $fullPath = $this->filePath; $this->close(); } else { if ($name === '') { $name = $this->varEntry['varname']; } $extIndex = $this->calcModel->getOrderId(); if ($extIndex < 0) { $extIndex = 0; } $fileName = str_replace("", '', $name) . '.' . $this->getType()->getExts()[$extIndex]; if ($directory === '') { $directory = './'; } $directory = rtrim($directory, '/'); $fullPath = realpath($directory) . '/' . $fileName; } $handle = fopen($fullPath, 'wb'); if (!$handle) { throw new \RuntimeException('Could not open destination file: ' . $fullPath); } $this->refreshMetadataFields(); $bin_data = ''; foreach ([$this->header, $this->varEntry] as $whichData) { foreach ($whichData as $key => $data) { // fields not used for this calc version, for instance. if ($data === null) { continue; } switch (gettype($data)) { case 'integer': // The length fields are the only ones on 2 bytes. if ($key === 'entries_len' || $key === 'data_length' || $key === 'data_length2') { $bin_data .= chr($data & 0xff) . chr($data >> 8 & 0xff); } else { $bin_data .= chr($data & 0xff); } break; case 'string': $bin_data .= $data; break; case 'array': foreach ($data as $subData) { $bin_data .= chr($subData & 0xff); } break; } } } fwrite($handle, $bin_data); fwrite($handle, chr($this->computedChecksum & 0xff) . chr($this->computedChecksum >> 8 & 0xff)); fclose($handle); $this->corrupt = false; }
private function makeVarEntryFromFile() { $calcFlags = $this->calcModel->getFlags(); $dataSectionOffset = 8 + 3 + 42 + 2; // after header fseek($this->file, $dataSectionOffset); $this->varEntry = []; $this->varEntry['constBytes'] = $this->get_raw_bytes(2); $this->varEntry['data_length'] = $this->get_raw_bytes(1)[0] + ($this->get_raw_bytes(1)[0] << 8); $this->varEntry['typeID'] = $this->get_raw_bytes(1)[0]; $this->varEntry['varname'] = $this->get_string_bytes(8); $this->varEntry['version'] = $calcFlags >= TIFeatureFlags::hasFlash ? $this->get_raw_bytes(1)[0] : null; $this->varEntry['archivedFlag'] = $calcFlags >= TIFeatureFlags::hasFlash ? $this->get_raw_bytes(1)[0] : null; $this->varEntry['data_length2'] = $this->get_raw_bytes(1)[0] + ($this->get_raw_bytes(1)[0] << 8); $this->varEntry['data'] = $this->get_raw_bytes($this->varEntry['data_length']); }