Skip to content

Commit b077490

Browse files
committed
Add support to process file async
1 parent 13c24cb commit b077490

File tree

3 files changed

+66
-10
lines changed

3 files changed

+66
-10
lines changed

demos/demo.php

+27-10
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,34 @@
33
require_once 'vendor/autoload.php';
44

55
use Terremoth\Async\Process;
6-
6+
use Terremoth\Async\File;
77

88
$process = new Process();
9-
echo time() . ' :: Sending process. You should not wait any longer to see next message: ' . PHP_EOL;
10-
$process->send(function () {
9+
echo date('c') . ' :: Sending process. You should not wait any longer to see next message: ' . PHP_EOL;
10+
try {
11+
$process->send(function () {
12+
13+
$var1 = 4;
14+
$var2 = 2 + 2;
15+
16+
sleep(5);
17+
18+
if ($var1 == $var2) {
19+
echo 2;
20+
file_put_contents('demo.txt', 'Hello, World! At: ' . date('c'));
21+
}
22+
});
23+
} catch (Exception $e) {
24+
echo $e->getMessage();
25+
}
1126

12-
sleep(5);
13-
if (1 == 1) {
14-
echo 2;
15-
file_put_contents('demo.txt', 'Hello, World!');
16-
}
17-
});
27+
echo date('c') . ' :: This is the next message' . PHP_EOL;
28+
echo date('c') . ' :: Now let\'s process a file that takes a long time...' . PHP_EOL;
1829

19-
echo time() . ' :: This is the next message' . PHP_EOL;
30+
try {
31+
$file = new File(__DIR__ . DIRECTORY_SEPARATOR . 'time-wasting-file.php');
32+
$file->run();
33+
echo date('c') . ' :: Ended...' . PHP_EOL;
34+
} catch (Exception $e) {
35+
echo $e->getMessage();
36+
}

demos/time-wasting-file.php

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
for ($i = 1; $i <= 5; $i++) {
4+
echo $i . '...' . PHP_EOL;
5+
sleep(1);
6+
}
7+
8+
file_put_contents('demo-file.txt', 'Hello users! At: ' . date('c'));

src/Terremoth/Async/File.php

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace Terremoth\Async;
4+
5+
use Exception;
6+
use Symfony\Component\Process\Process as SymfonyProcess;
7+
8+
class File
9+
{
10+
/**
11+
* @throws Exception
12+
*/
13+
public function __construct(private readonly string $file, private readonly array $args = [])
14+
{
15+
if (!is_readable($this->file)) {
16+
throw new Exception('File ' . $this->file . ' does not exists or is not readable!');
17+
}
18+
}
19+
20+
public function run(): int
21+
{
22+
$template = [PHP_BINARY, $this->file, ...$this->args, '&'];
23+
24+
if (PHP_OS_FAMILY === 'Windows') {
25+
$template = ['start', '""', '/B', PHP_BINARY, $this->file, ...$this->args];
26+
}
27+
28+
$process = new SymfonyProcess($template);
29+
return $process->run();
30+
}
31+
}

0 commit comments

Comments
 (0)