Skip to content

Commit

Permalink
Introduce the JsonlParser::fromFile() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
macbre committed Nov 29, 2023
1 parent ec76635 commit c6ba82d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
9 changes: 9 additions & 0 deletions src/JsonlParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ public function __construct(protected $stream)
{
}

/**
* Initialize the parser from the given file.
*/
public static function fromFile(string $filename, string $mode = 'a+t'): self
{
$stream = fopen($filename, $mode);
return new self($stream);
}

public function push(array|string $item): void
{
$encoded = json_encode($item);
Expand Down
7 changes: 2 additions & 5 deletions tests/JsonParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,11 @@ public function testPushItemsToFile(): void
fclose($stream); // this removes the file
}

public function testFileSyncing(): void
public function testFromFile(): void
{
$tmpFilename = tempnam(directory: sys_get_temp_dir(), prefix: 'jsonld');
$stream = fopen($tmpFilename, 'a+t');

// TODO: introduce a helper JsonlParser::fromFile()
$parser = new JsonlParser($stream);
$parser = JsonlParser::fromFile($tmpFilename);
$this->assertCount(0, $parser);
$this->assertTrue($parser->empty());

Expand Down Expand Up @@ -166,7 +164,6 @@ public function testFileSyncing(): void
actualString: ''
);

fclose($stream);
unlink($tmpFilename);
}
}

0 comments on commit c6ba82d

Please sign in to comment.