Completed
Pull Request — master (#59)
by Julien
02:49
created

ReplyAggregator::getNextFileName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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