handle = $handle; $this->pos = (int) ftell( $handle ); } public function offset(): int { return $this->pos; } public function writeMagic(): void { $this->put( Format::MAGIC ); } public function beginEntry( string $name, int $size, int $mtime ): void { $this->put( Format::header( $name, $size, $mtime ) ); } public function write( string $bytes ): void { $this->put( $bytes ); } /** * Convenience for small in-memory entries such as package.json. */ public function addString( string $name, string $contents ): void { $this->beginEntry( $name, strlen( $contents ), time() ); $this->write( $contents ); } public function writeEof( int $entries ): void { $this->put( Format::eof( $entries ) ); } /** * Fails if the file is not exactly where an entry's declared length says it should be. The header * promises "s" payload bytes; if the file ever disagrees, every later header would land inside * payload data. Stopping here names the file instead of producing an archive that fails to restore. * * @throws \RuntimeException */ public function assertOffset( int $expected, string $entry_name ): void { if ( $this->pos !== $expected ) { throw new \RuntimeException( sprintf( 'Archive write mismatch on %s: expected the file to end at byte %d but it is at %d.', esc_html( $entry_name ), (int) $expected, (int) $this->pos ) ); } } /** * Fails if the file on disk is not exactly as long as this writer has made it. Only this writer * appends to the archive, so any other length means a second process is writing or truncating it * (a retried request that ran alongside the first). Continuing would interleave two sets of bytes * and shift every later header, so the caller must back off instead. * * @throws ArchiveConflictException */ public function assertExclusive(): void { $stat = fstat( $this->handle ); if ( false === $stat || $stat['size'] !== $this->pos ) { throw new ArchiveConflictException( sprintf( 'The archive is %d bytes on disk but this writer expected %d: another process is writing to it.', false === $stat ? -1 : (int) $stat['size'], (int) $this->pos ) ); } } /** * Cuts the archive back to an earlier offset, used to abandon a half-written entry. */ public function truncateTo( int $offset ): void { ftruncate( $this->handle, $offset ); $this->pos = $offset; } public function flush(): void { fflush( $this->handle ); } /** * Every write goes to the offset this writer tracks, set explicitly. The position is never taken * from wherever the stream happens to be, so a stream that was moved or a retried tick cannot * append at the wrong place. */ private function put( string $bytes ): void { if ( 0 !== fseek( $this->handle, $this->pos, SEEK_SET ) ) { throw new \RuntimeException( sprintf( 'Cannot seek to byte %d of the archive.', (int) $this->pos ) ); } SafeFile::writeAll( $this->handle, $bytes ); $this->pos += strlen( $bytes ); } }