permafrost-dev/code-snippets

Repository files navigation

Package VersionlicenseTest Run Statuscode coverage

Easily work with snippets of code from source code files.

The original code this package is based on was borrowed from the spatie/backtrace package.

You can install the package via composer:

composer require permafrost-dev/code-snippets

Use the surroundingLine($num) method to select the "target" line, which will be returned as the middle line of the snippet:

use Permafrost\CodeSnippets\CodeSnippet;

$snippet = (new CodeSnippet())
    ->surroundingLine(4)
    ->snippetLineCount(6)
    ->fromFile('/path/to/a/file.php');

Use the surroundingLines($first, $last) method to select a range of "target" lines, which will be returned as the middle lines of the snippet:

use Permafrost\CodeSnippets\CodeSnippet;

$snippet = (new CodeSnippet())
    ->surroundingLines(4, 7)
    ->snippetLineCount(6)
    ->fromFile('/path/to/a/file.php');

Use the linesBefore() and linesAfter() methods to specify the number of context lines to display before and after the "target" lines:

use Permafrost\CodeSnippets\CodeSnippet;

// the "target" line isn't displayed in the middle, but as the second line
$snippet = (new CodeSnippet())
    ->surroundingLine(4)
    ->linesBefore(1)
    ->linesAfter(3)
    ->fromFile('/path/to/a/file.php');

The getLines() method returns an array of SnippetLine instances. The keys of the resulting array are the line numbers.

The SnippetLine instances may be cast to strings to display the value.

use Permafrost\CodeSnippets\CodeSnippet;

// the "target" line isn't displayed in the middle, but as the second line
$snippet = (new CodeSnippet())
    ->surroundingLine(4)
    ->snippetLineCount(5)
    ->fromFile('/path/to/a/file.php');
    
foreach($snippet->getLines() as $lineNum => $line) {
    // use ->isSelected() to determine if the line was selected using the
    // surroundingLine() or surroundingLines() method
    $prefix = $line->isSelected() ? ' * ' : '   ';
    
    echo "{$prefix}{$line->lineNumber()} - {$line}" . PHP_EOL;
    // or
    echo $prefix . $line->lineNumber() . ' - ' . $line->value() . PHP_EOL;
}
./vendor/bin/phpunit

Please see CHANGELOG for more information on what has changed recently.

Please see CONTRIBUTING for details.

Please review our security policy on how to report security vulnerabilities.

The MIT License (MIT). Please see License File for more information.

About

Easily create and work with code snippets from PHP

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  

Contributors 2

  •  
  •  

Languages