Csv::getFilePath()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bex\Behat\StepTimeLoggerExtension\Service\OutputPrinter;
4
5
use Bex\Behat\StepTimeLoggerExtension\ServiceContainer\Config;
6
use Symfony\Component\Console\Output\ConsoleOutput;
7
use Symfony\Component\Filesystem\Filesystem;
8
9
class Csv implements OutputPrinterInterface
10
{
11
    const FILE_NAME_PATTERN = 'step-times-%s.csv';
12
13
    /**
14
     * @var string
15
     */
16
    private $outputDirectory;
17
18
    /**
19
     * @var ConsoleOutput
20
     */
21
    private $output;
22
23
    /**
24
     * @var Filesystem
25
     */
26
    private $filesystem;
27
28
    /**
29
     * @param ConsoleOutput $output
30
     */
31
    public function __construct(ConsoleOutput $output, Filesystem $filesystem)
32
    {
33
        $this->output = $output;
34
        $this->filesystem = $filesystem;
35
    }
36
37
    /**
38
     * @param Config $config
39
     */
40
    public function configure(Config $config)
41
    {
42
        $this->outputDirectory = $config->getOutputDirectory();
43
    }
44
45
    /**
46
     * @param \Generator $avgTimes
47
     *
48
     * @return void
49
     */
50
    public function printLogs(\Generator $avgTimes)
51
    {
52
        $filePath = $this->getFilePath();
53
        $this->filesystem->dumpFile($filePath, '');
54
        $file = fopen($filePath, 'w');
55
56
        if ($file === false) {
57
            throw new \InvalidArgumentException(sprintf('Cannot open %s for writting', $filePath));
58
        }
59
60
        fputcsv($file, ['Average execution Time', 'Called count', 'Total Cost', 'Step name']);
61
62
        foreach ($avgTimes as $stepName => $info) {
63
            fputcsv($file, [$info['avg_execution_time'], $info['total_executions'], $info['total_cost'], $stepName]);
64
        }
65
66
        fclose($file);
67
68
        $this->output->writeln('Step time log has been saved. Open at ' . $filePath);
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    private function getFilePath()
75
    {
76
        $fileName = sprintf(self::FILE_NAME_PATTERN, time());
77
        $path = rtrim($this->outputDirectory, DIRECTORY_SEPARATOR);
78
        return empty($path) ? $fileName : $path . DIRECTORY_SEPARATOR . $fileName;
79
    }
80
81
82
}
83