Skip to content

Commit

Permalink
feature: mark repeating lines with repeating character
Browse files Browse the repository at this point in the history
  • Loading branch information
g105b committed Jul 15, 2024
1 parent 42aeef2 commit 61efab7
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
23 changes: 22 additions & 1 deletion src/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ class Stream {
const IN = "in";
const OUT = "out";
const ERROR = "error";
const REPEAT_CHAR = "";

protected SplFileObject $error;
protected SplFileObject $out;
protected SplFileObject $in;
protected SplFileObject $currentStream;

protected string $lastLineBuffer;
private bool $lastLineRepeats;

public function __construct(
string $in = null,
string $out = null,
Expand All @@ -29,6 +33,8 @@ public function __construct(
}

$this->setStream($in, $out, $error);
$this->lastLineBuffer = "";
$this->lastLineRepeats = false;
}

public function setStream(string $in, string $out, string $error):void {
Expand Down Expand Up @@ -81,7 +87,22 @@ public function writeLine(
string $message = "",
string $streamName = self::OUT
):void {
$this->write($message . PHP_EOL, $streamName);
$message .= PHP_EOL;

if($message === $this->lastLineBuffer) {
$this->write(self::REPEAT_CHAR, $streamName);
$this->lastLineRepeats = true;
}
else {
if($this->lastLineRepeats) {
$this->write(PHP_EOL, $streamName);
}

$this->write($message, $streamName);
$this->lastLineRepeats = false;
}

$this->lastLineBuffer = $message;
}

protected function getNamedStream(string $streamName):SplFileObject {
Expand Down
30 changes: 29 additions & 1 deletion test/phpunit/StreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,32 @@ public function testInvalidStreamName() {
$this->expectException(InvalidStreamNameException::class);
$stream->write("this does not exist", "nothing");
}
}

public function testRepeatingLineSuppressed():void {
$stream = new Stream(
"php://memory",
"php://memory",
"php://memory",
);
$out = $stream->getOutStream();

for($i = 1; $i <= 10; $i++) {
$stream->writeLine("This is message $i, and should appear individually.");
}

for($i = 1; $i <= 5; $i++) {
$stream->writeLine("This message is sent 5 times but should only appear once.");
}

for($i = 11; $i <= 20; $i++) {
$stream->writeLine("This is message $i, and should appear after the repeating message individually.");
}

$out->rewind();
$fullStreamContents = $out->fread(1024);

self::assertSame(10, substr_count($fullStreamContents, "should appear individually"), "Unique messages should appear individually");
self::assertSame(1, substr_count($fullStreamContents, "should only appear once"), "Similar messages should only appear once");
self::assertSame(4, substr_count($fullStreamContents, Stream::REPEAT_CHAR));
}
}

0 comments on commit 61efab7

Please sign in to comment.