diff --git a/CHANGELOG.md b/CHANGELOG.md index 797e0f8..3fc34f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/CodeSnippet.php b/src/CodeSnippet.php index 86cf34e..efee708 100644 --- a/src/CodeSnippet.php +++ b/src/CodeSnippet.php @@ -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); diff --git a/tests/CodeSnippetTest.php b/tests/CodeSnippetTest.php index f8617aa..b2c2ffb 100644 --- a/tests/CodeSnippetTest.php +++ b/tests/CodeSnippetTest.php @@ -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); + } } diff --git a/tests/__snapshots__/CodeSnippetTest__it_returns_a_string_when_the_snippet_is_cast_to_a_string__1.txt b/tests/__snapshots__/CodeSnippetTest__it_returns_a_string_when_the_snippet_is_cast_to_a_string__1.txt new file mode 100644 index 0000000..36fecd5 --- /dev/null +++ b/tests/__snapshots__/CodeSnippetTest__it_returns_a_string_when_the_snippet_is_cast_to_a_string__1.txt @@ -0,0 +1,8 @@ + /** + @var Ray $ray + */ + $ray = ray()->text('hello world') + ->blue() + ->large(); + + Ray diff --git a/tests/__snapshots__/CodeSnippetTest__it_returns_the_snippet_as_a_string__1.txt b/tests/__snapshots__/CodeSnippetTest__it_returns_the_snippet_as_a_string__1.txt new file mode 100644 index 0000000..36fecd5 --- /dev/null +++ b/tests/__snapshots__/CodeSnippetTest__it_returns_the_snippet_as_a_string__1.txt @@ -0,0 +1,8 @@ + /** + @var Ray $ray + */ + $ray = ray()->text('hello world') + ->blue() + ->large(); + + Ray