stream = $stream; $this->lineLength = $lineLength; $this->lineEnding = $lineEnding; $this->lineEndingLength = \strlen($this->lineEnding); } /** * Inserts the line ending character after each line length characters in * the passed string, making sure previously written bytes are taken into * account. */ private function getChunkedString(string $string): string { $firstLine = ''; if ($this->tell() !== 0) { $next = $this->lineLength - ($this->position % ($this->lineLength + $this->lineEndingLength)); if (\strlen($string) > $next) { $firstLine = \substr($string, 0, $next).$this->lineEnding; $string = \substr($string, $next); } } // chunk_split always ends with the passed line ending $chunked = $firstLine.\chunk_split($string, $this->lineLength, $this->lineEnding); return \substr($chunked, 0, \strlen($chunked) - $this->lineEndingLength); } /** * Writes the passed string to the underlying stream, ensuring line endings * are inserted every "line length" characters in the string. * * @param string $string * * @return int number of bytes written */ public function write($string): int { $chunked = $this->getChunkedString($string); $this->position += \strlen($chunked); return $this->stream->write($chunked); } /** * Inserts a final line ending character. */ private function beforeClose(): void { if ($this->position !== 0) { $this->stream->write($this->lineEnding); } } /** * @inheritDoc */ public function close(): void { $this->beforeClose(); $this->stream->close(); } /** * @inheritDoc */ public function detach() { $this->beforeClose(); $this->stream->detach(); return null; } }