Completed
Push — master ( b56704...b07206 )
by David
14s queued 10s
created

ReplyAggregator::storeReply()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace TheAentMachine;
5
6
/**
7
 * Class in charge of assembling replies from the different containers.
8
 */
9
class ReplyAggregator
10
{
11
    /**
12
     * @var string
13
     */
14
    private $replyDirectory;
15
16
    public function __construct(string $replyDirectory = null)
17
    {
18
        if ($replyDirectory === null) {
19
            $replyDirectory = \sys_get_temp_dir().'/replies';
20
        }
21
        $this->replyDirectory = rtrim($replyDirectory, '/').'/';
22
        if (!\file_exists($replyDirectory)) {
23
            \mkdir($replyDirectory, 0777, true);
24
        }
25
    }
26
27
    /**
28
     * Purges all received replies
29
     */
30
    public function clear(): void
31
    {
32
        $files = glob($this->replyDirectory.'*'); // get all file names
33
        foreach ($files as $file) { // iterate files
34
            if (is_file($file)) {
35
                unlink($file); // delete file
36
            }
37
        }
38
    }
39
40
    private function getNextFileName(): string
41
    {
42
        $i = 0;
43
        while (\file_exists($this->replyDirectory.'tmp'.$i)) {
44
            $i++;
45
        }
46
        return 'tmp'.$i;
47
    }
48
49
    public function storeReply(string $payload): void
50
    {
51
        $path = $this->replyDirectory.$this->getNextFileName();
52
        \file_put_contents($path, $payload);
53
    }
54
55
    /**
56
     * @return string[]
57
     */
58
    public function getReplies(): array
59
    {
60
        $i = 0;
61
        $replies = [];
62
        while (\file_exists($this->replyDirectory.'tmp'.$i)) {
63
            $replies[] = \file_get_contents($this->replyDirectory.'tmp'.$i);
64
            $i++;
65
        }
66
        return $replies;
67
    }
68
}
69