Optimized way to get just the last few entries of a log file

@param string $filepath
@param int $lines
@return bool|string
765133
public function tail($filepath, $lines = 1) {

        $f = @fopen($filepath, "rb");
        if ($f === false) return false;

        else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));

        fseek($f, -1, SEEK_END);
        if (fread($f, 1) != "\n") $lines -= 1;

        // Start reading
        $output = '';
        $chunk = '';
        // While we would like more
        while (ftell($f) > 0 && $lines >= 0) {
            // Figure out how far back we should jump
            $seek = min(ftell($f), $buffer);
            // Do the jump (backwards, relative to where we are)
            fseek($f, -$seek, SEEK_CUR);
            // Read a chunk and prepend it to our output
            $output = ($chunk = fread($f, $seek)) . $output;
            // Jump back to where we started reading
            fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
            // Decrease our line counter
            $lines -= substr_count($chunk, "\n");
        }
        // While we have too many lines
        // (Because of buffer size we might have read too many)
        while ($lines++ < 0) {
            // Find first newline and remove all text before that
            $output = substr($output, strpos($output, "\n") + 1);
        }
        // Close file and return
        fclose($f);

        return trim($output);
    }
61225
private function getSharedStimulusFile($filePath)
    {
        \helpers_TimeOutHelper::setTimeOutLimit(\helpers_TimeOutHelper::LONG);
        $extractPath = $this->extractArchive($filePath);
        \helpers_TimeOutHelper::reset();

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($extractPath),
            \RecursiveIteratorIterator::LEAVES_ONLY);

        /** @var $file \SplFileInfo */
        foreach ($iterator as $file) {
            //check each file to see if it can be the shared stimulus file
            if ($file->isFile()) {
                if (preg_match('/^[\w]/', $file->getFilename()) === 1 && $file->getExtension() === 'xml') {
                    return $file->getRealPath();
                }
            }
        }

        throw new \common_Exception('XML not found in the package');
    }
1087615
public static function getIncludePath($filepath)
    {
        static $_include_path = null;

        if ($_path_array === null) {
            $_include_path = explode(PATH_SEPARATOR, get_include_path());
        }

        foreach ($_include_path as $_path) {
            if (file_exists($_path . DS . $filepath)) {
                return $_path . DS . $filepath;
            }
        }
        
        return false;
    }
1021045
protected function getCodeSnippet($filePath, $lineNumber, $linesBefore = 3, $linesAfter = 3)
    {
        $lines = file($filePath);
        $offset = $lineNumber - $linesBefore - 1;
        $offset = max($offset, 0);
        $length = $linesAfter + $linesBefore + 1;
        $lines = array_slice($lines, $offset, $length, $preserveKeys = true);
        end($lines);
        $lineStrlen = strlen(key($lines) + 1);
        $snippet = '';

        foreach ($lines as $i => $line) {
            $snippet .= (abs($lineNumber) === $i + 1 ? '  > ' : '    ');
            $snippet .= str_pad($i + 1, $lineStrlen, ' ', STR_PAD_LEFT).'| '.rtrim($line).PHP_EOL;
        }

        return $snippet;
    }
139359
protected function backupFile($filePath)
    {
        $sourcePath = $filePath;
        $backupPath = $filePath.'.bak';

        if (file_exists($backupPath)) {
            $date = new \DateTime();
            $backupPath = "{$filePath}{$date->getTimestamp()}.bak";
        }

        copy($sourcePath, $backupPath);

        return $backupPath;
    }
465003
protected function readFile(string $filePath): string
    {
        /**
         * read bin
         */
        $handle = fopen($filePath, 'rb');
        $stream = fread($handle, $this->maxByteCacheLen);
        fclose($handle);
        return $stream;
    }
365903
protected function removeTemporaryFiles($filepath, $force = false)
	{
		if ($force || $filepath !== $this->getUncompressedFilepath($filepath)) {
			$this->getBackupFilesystemInstance()->removeFile($this->getUncompressedFilepath($filepath));
		}
	}
372996
public function getFileContent($filePath)
    {
        if ($this->repository->fileExists($filePath) === false) {
            throw new Exception(sprintf('The file "%s" cannot be found', $filePath));
        }
        return $this->repository->getFileContent($filePath);
    }
449699
public function write($filePath, array $entries)
    {
        $handle = $this->openFile($filePath);

        $entriesCount = count($entries);
        $counter = 0;
        foreach ($entries as $entry) {
            $entryStr = $this->getEntryStr($entry, $counter, $entriesCount);
            fwrite($handle, $entryStr);

            $counter++;
        }

        fclose($handle);
    }
1137135
public static function last_lines($path, $line_count, $offset = 0, $block_size = 512){
		$lines = array();
	
		// we will always have a fragment of a non-complete line
		// keep this in here till we have our next entire line.
		$leftover = "";
	
		$fh = fopen($path, 'r');
		$storeOffset = $offset;
		// go to the end of the file
		fseek($fh, $offset, SEEK_END);
		do{
			// need to know whether we can actually go back
			// $block_size bytes
			$can_read = $block_size;
			if(ftell($fh) < $block_size){
				$can_read = ftell($fh);
			}
			$storeOffset -= $can_read;
			// go back as many bytes as we can
			// read them to $data and then move the file pointer
			// back to where we were.
			fseek($fh, -$can_read, SEEK_CUR);
			$data = @fread($fh, $can_read);
			$data .= $leftover;
			fseek($fh, -$can_read, SEEK_CUR);
	
			// split lines by \n. Then reverse them,
			// now the last line is most likely not a complete
			// line which is why we do not directly add it, but
			// append it to the data read the next time.
			$split_data = array_reverse(explode("\n", $data));
			$new_lines = array_slice($split_data, 0, -1);
			$lines = array_merge($lines, $new_lines);
			$leftover = $split_data[count($split_data) - 1];
		}
		while(count($lines) < $line_count && ftell($fh) != 0);
		if(ftell($fh) == 0){
			$lines[] = $leftover;
		}
		fclose($fh);
		// Usually, we will read too many lines, correct that here.
		return [ 'lines' => array_slice($lines, 0, $line_count),
				 'offset' => $storeOffset 
		];
	}
622733
public function getFileHistory(FilePath $path, $maxCount = null)
    {
        return $this->gitService->getFileHistory($path, $maxCount);
    }
996076
public function archive($filepath)
	{
		if ( ! ($fp = @fopen($filepath, 'w+b')))
		{
			return FALSE;
		}

		flock($fp, LOCK_EX);

		for ($result = $written = 0, $data = $this->get_zip(), $length = strlen($data); $written < $length; $written += $result)
		{
			if (($result = fwrite($fp, substr($data, $written))) === FALSE)
			{
				break;
			}
		}

		flock($fp, LOCK_UN);
		fclose($fp);

		return is_int($result);
	}
768159
public function obfuscate($filePath)
    {
        if (trim($filePath) == "") {
            $this->_errors[] = "File Name cannot be blank in function: " .
                __FUNCTION__;
            return false;
        }
        if (!is_readable($filePath)) {
            $this->_errors[] = "Failed to open file: $filePath in the function: " .
                __FUNCTION__;
            return false;
        }

        $this->_fileName = trim($filePath);
        $name = explode(".", $this->_fileName);
        $ext = end($name);
        $pos = strrpos($this->_fileName, ".");

        $filePath = substr($this->_fileName, 0, $pos);

        $this->_obfuscateFileName = $obfuscateFileName = $filePath . "." .
            $this->_obfuscatedFileSuffix . "." . $ext;

        if (($fp = fopen($obfuscateFileName, "w+")) === false) {
            $this->_errors[] = "Failed to open file: $obfuscateFileName " .
                "for writing in the function: " . __FUNCTION__;
            return false;
        } else {

            fwrite($fp, "<?php \r\n");
            $line = php_strip_whitespace($this->_fileName);

            $line = $this->preProcessString($line);
            $line = $this->encodeString($line);
            $line .= "\r\n";
            fwrite($fp, $line);
        }

        fclose($fp);

        return $obfuscateFileName;
    }
320815
public function extract($filePath)
    {
        $directory = $this->directory->getDirectoryPath();
        $rarArchive = RarArchive::open($filePath);
        $rarEntries = $rarArchive->getEntries();

        /**
         * @var RarEntry $rarEntiry
         */
        foreach ($rarEntries as $rarEntry) {

            $rarEntry->extract($directory);
        }

        return $this->createFinderFromDirectory($directory);
    }
1276972
protected function getFileAsset($filePath)
    {
        $file = new \SplFileInfo($filePath);

        if (!$file->isReadable() || $file->isDir()) {
            return null;
        }

        $filePath = $file->getRealPath();

        return new FileAsset($filePath);
    }
434267
public static function close(string $filepath):int
    {
        if (self::$file != null) {
            self::$filepath = null;
            self::$file = null;
        }
        return (1);
    }
1069100
public static function openFile($filepath)
    {
        $contents = null;

        if ($realPath = realpath($filepath)) {
            $handle = fopen($realPath, 'rb');
            $contents = fread($handle, filesize($realPath));
            fclose($handle);
        }

        return $contents;
    }