TimerEvent::asArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace IntegerNet\DeployerTimer;
5
6
class TimerEvent
7
{
8
    public const TYPE_BEGIN = 'BEGIN';
9
    public const TYPE_END = 'END';
10
    /**
11
     * @var string
12
     */
13
    private $type;
14
    /**
15
     * @var string
16
     */
17
    private $taskName;
18
    /**
19
     * @var float
20
     */
21
    private $timestamp;
22
    /**
23
     * @var float
24
     */
25
    private $duration;
26
27 9
    public function __construct(string $type, string $taskName, float $timestamp, float $duration)
28
    {
29 9
        $this->type = $type;
30 9
        $this->taskName = $taskName;
31 9
        $this->timestamp = $timestamp;
32 9
        $this->duration = $duration;
33 9
    }
34
35 9
    private function asArray()
36
    {
37 9
        return [$this->type, $this->taskName, round($this->timestamp, 3), round($this->duration, 3)];
38
    }
39
40 9
    public function asCsvLine(): string
41
    {
42 9
        $csvStream = fopen('php://memory', 'rb+');
43 9
        if ($csvStream === false) {
44
            throw new \RuntimeException('Could not open temporary stream');
45
        }
46
        try {
47 9
            if (fputcsv($csvStream, $this->asArray()) === false) {
48
                throw new \RuntimeException('Could not format TimerEvent as CSV');
49
            }
50 9
            rewind($csvStream);
51 9
            $line = stream_get_contents($csvStream);
52 9
            if ($line === false) {
53
                throw new \RuntimeException('Could not read from temporary CSV stream');
54
            }
55 9
        } finally {
56 9
            fclose($csvStream);
57
        }
58 9
        return rtrim($line);
59
    }
60
}
61