Completed
Push — master ( 301313...fef224 )
by Florian
03:10
created

Writer::render()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 1
crap 3
1
<?php
2
3
namespace Cocur\Arff;
4
5
/**
6
 * ArffWriter.
7
 *
8
 * @author    Florian Eckerstorfer
9
 * @copyright 2015-2017 Florian Eckerstorfer
10
 */
11
class Writer
12
{
13
    /**
14
     * @param Document $document
15
     * @param array    $row
16
     *
17
     * @return string
18
     */
19 1
    public function renderRow(Document $document, $row)
20
    {
21 1
        $processedRow = [];
22 1
        foreach ($document->getColumns() as $name => $column) {
23 1
            $value = $row[$name];
24 1
            if (preg_match('/\s|,|;/', $value)) {
25 1
                $value = sprintf("'%s'", $value);
26
            }
27 1
            $processedRow[] = $value;
28
        }
29
30 1
        return sprintf("%s\n", implode(',', $processedRow));
31
    }
32
33
    /**
34
     * @param Document $document
35
     *
36
     * @return string
37
     */
38 1
    public function render(Document $document)
39
    {
40 1
        $content = sprintf("@RELATION %s\n\n", $document->getName());
41 1
        foreach ($document->getColumns() as $name => $column) {
42 1
            $content .= $column->render()."\n";
43
        }
44 1
        $content .= "\n@DATA\n";
45 1
        foreach ($document->getData() as $row) {
46 1
            $content .= $this->renderRow($document, $row);
47
        }
48
49 1
        return $content;
50
    }
51
52
    /**
53
     * @param Document $document
54
     * @param string   $filename
55
     *
56
     * @return Writer
57
     */
58 1
    public function write(Document $document, $filename)
59
    {
60 1
        file_put_contents($filename, $this->render($document));
61
62 1
        return $this;
63
    }
64
}
65