Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save katanacrimson/407248 to your computer and use it in GitHub Desktop.
Save katanacrimson/407248 to your computer and use it in GitHub Desktop.
<?php
/**
* Retrieves the context code from where an error/exception was thrown (as long as file/line are provided) and outputs it.
* @param string $file - The file where the error/exception occurred.
* @param string $line - The line where the error/exception occurred.
* @param integer $context - How many lines of context (above AND below) the troublemaker should we grab?
* @return string - String containing the perpetrator + context lines for where the error/exception was thrown.
*/
function getErrorContext($file, $line, $context = 3)
{
$return = '';
$line_i = 0;
if($fh = fopen($file,"r"))
{
while (!feof($fh))
{
$line_i++;
if($line_i > ($line - $context))
{
if($line_i < ($line + $context))
break;
$return[] = fgets($fh);
}
else
{
fgets($fh);
}
}
fclose($fh);
}
return $return;
}
try
{
// blah blah 123
throw new Exception('test');
}
catch(Exception $e)
{
echo $e . PHP_EOL . 'Exception context:' . PHP_EOL . implode('', getErrorContext($e->getFile(), $e->getLine(), 4));
}
// blah blah
@katanacrimson
Copy link
Author

This uses less memory. file() will store every line as an array (leaving it up to us to cut out the stuff we need, which means an additional loop to rip out what we want since file() is a loop in itself) versus this method, which just doesn't store the value returned from fgets() except for the lines we want.

As for the first param for implode, meh. I tried using "\n" initially, but didn't need it, so left it as ''. :P

@HighwayofLife
Copy link

file_get_contents() and file() read files into the buffer - a single string, so they are faster for small files, but are very bad for large files and therefore consume more memory. Functions such as fgets() read files line-by-line, so you won’t run into the buffer, the downside is that it is slower, but you can read larger files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment