$offset ) { $fh = fopen( $path, 'r+b' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( $fh ) { ftruncate( $fh, (int) $offset ); fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose // PHP 7.4 keeps the old size in its stat cache after ftruncate(): a filesize() after // this would still see the discarded rows (CI caught it on the 6.4 / 7.4 job). clearstatcache( true, $path ); } } } /** * Reads up to $limit rows starting at a byte offset. * * @param string $path Absolute path. * @param int $offset Byte offset. * @param int $limit Max rows. * @return array{rows: array[], ends: int[], next: int, eof: bool} */ public static function read( $path, $offset, $limit ) { $out = array( 'rows' => array(), 'ends' => array(), 'next' => (int) $offset, 'eof' => true, ); if ( ! is_readable( $path ) ) { return $out; } $fh = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( ! $fh ) { return $out; } fseek( $fh, (int) $offset ); while ( count( $out['rows'] ) < $limit ) { $line = fgets( $fh ); if ( false === $line ) { break; } if ( "\n" !== substr( $line, -1 ) ) { break; // Partial line from an interrupted writer: stop before it. } $out['next'] += strlen( $line ); $row = json_decode( $line, true ); if ( is_array( $row ) ) { $out['rows'][] = $row; $out['ends'][] = $out['next']; } } $out['eof'] = feof( $fh ) || false === fgets( $fh ); fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose return $out; } }