Skip to content

Commit 97293ab

Browse files
authored
Merge pull request #32 from DirectoryTree/mbox-reader
Add `.mbox` file reader
2 parents 9d9bf0e + f8be9de commit 97293ab

File tree

4 files changed

+8632
-0
lines changed

4 files changed

+8632
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"egulias/email-validator": "^4.0"
2626
},
2727
"require-dev": {
28+
"spatie/ray": "^1.0",
2829
"pestphp/pest": "^2.0|^3.0"
2930
},
3031
"autoload": {

src/Mbox.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace DirectoryTree\ImapEngine;
4+
5+
use DirectoryTree\ImapEngine\Exceptions\RuntimeException;
6+
use Generator;
7+
8+
class Mbox
9+
{
10+
/**
11+
* Constructor.
12+
*/
13+
public function __construct(
14+
protected string $filepath
15+
) {}
16+
17+
/**
18+
* Get the messages from the mbox file.
19+
*/
20+
public function messages(): Generator
21+
{
22+
if (! $handle = fopen($this->filepath, 'r')) {
23+
throw new RuntimeException('Failed to open mbox file: '.$this->filepath);
24+
}
25+
26+
$buffer = '';
27+
28+
while (($line = fgets($handle)) !== false) {
29+
if (str_starts_with($line, 'From ') && $buffer !== '') {
30+
yield new FileMessage($buffer);
31+
32+
$buffer = '';
33+
}
34+
35+
$buffer .= $line;
36+
}
37+
38+
if ($buffer !== '') {
39+
yield new FileMessage($buffer);
40+
}
41+
42+
fclose($handle);
43+
}
44+
}

0 commit comments

Comments
 (0)