Skip to content

Add toString method #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to `code-snippets` will be documented in this file.

## 1.1.0 - 2021-07-25

- add `toString()` and `__toString()` methods

## 1.0.2 - 2021-07-25

- fix minor bugs, refactor line boundary calculations
Expand Down
16 changes: 16 additions & 0 deletions src/CodeSnippet.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,22 @@ public function getLineNumberEnd(): int
return $this->surroundingLines[count($this->surroundingLines) - 1] ?? 0;
}

public function toString()
{
$result = '';

foreach ($this->getLines() as $line) {
$result .= $line->value() . PHP_EOL;
}

return $result;
}

public function __toString()
{
return $this->toString();
}

protected function isSurroundedLineNumber(int $lineNumber): bool
{
return in_array($lineNumber, $this->surroundingLines, true);
Expand Down
22 changes: 22 additions & 0 deletions tests/CodeSnippetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,26 @@ public function it_ensures_the_entire_surrounding_lines_are_displayed()

$this->assertMatchesSnapshot($snippet->getLines());
}

/** @test */
public function it_returns_the_snippet_as_a_string()
{
$snippet = (new CodeSnippet())
->surroundingLines(10, 12)
->snippetLineCount(8)
->fromFile($this->testsPath('data/file3.php'));

$this->assertMatchesSnapshot($snippet->toString());
}

/** @test */
public function it_returns_a_string_when_the_snippet_is_cast_to_a_string()
{
$snippet = (new CodeSnippet())
->surroundingLines(10, 12)
->snippetLineCount(8)
->fromFile($this->testsPath('data/file3.php'));

$this->assertMatchesSnapshot((string)$snippet);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
@var Ray $ray
*/
$ray = ray()->text('hello world')
->blue()
->large();

Ray
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
@var Ray $ray
*/
$ray = ray()->text('hello world')
->blue()
->large();

Ray