QueryExporter::export()   B
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
c 0
b 0
f 0
rs 8.8571
cc 5
eloc 12
nc 6
nop 1
1
<?php
2
3
namespace Graze\DataDb\Export\Query;
4
5
use Graze\DataDb\QueryNodeInterface;
6
use Graze\DataFile\Format\FormatAwareInterface;
7
use Graze\DataFile\Format\FormatInterface;
8
use Graze\DataFile\Format\JsonFormat;
9
use Graze\DataFile\Helper\Builder\BuilderAwareInterface;
10
use Graze\DataFile\Helper\Builder\BuilderTrait;
11
use Graze\DataFile\Helper\FileHelper;
12
use Graze\DataFile\Helper\OptionalLoggerTrait;
13
use Graze\DataFile\IO\FileWriter;
14
use Graze\DataFile\Node\FileNodeInterface;
15
use Psr\Log\LogLevel;
16
17
class QueryExporter implements QueryExporterInterface, BuilderAwareInterface
18
{
19
    use BuilderTrait;
20
    use OptionalLoggerTrait;
21
    use FileHelper;
22
23
    const PATH_TMP = '/tmp/export/query/';
24
25
    /** @var FileNodeInterface */
26
    private $file;
27
    /** @var FormatInterface|null */
28
    private $format;
29
30
    /**
31
     * QueryExporter constructor.
32
     *
33
     * @param FileNodeInterface|null $file
34
     * @param FormatInterface|null   $format
35
     */
36
    public function __construct(
37
        FileNodeInterface $file = null,
38
        FormatInterface $format = null
39
    ) {
40
        $this->file = $file;
41
        $this->format = $format;
42
    }
43
44
    /**
45
     * Export a table to something
46
     *
47
     * @param QueryNodeInterface $query
48
     *
49
     * @return FileNodeInterface
50
     */
51
    public function export(QueryNodeInterface $query)
52
    {
53
        $this->file = $this->file ?: $this->getTemporaryFile(static::PATH_TMP);
54
55
        if (is_null($this->format)) {
56
            if ($this->file instanceof FormatAwareInterface
57
                && $this->file->getFormatType()
58
            ) {
59
                $this->format = $this->file->getFormat();
60
            } else {
61
                $this->setDefaultFormat();
62
            }
63
        }
64
65
        $writer = $this->getBuilder()->build(FileWriter::class, $this->file, $this->format);
66
67
        $this->log(LogLevel::INFO, "Exporting generic query to file: {file}", ['file' => $this->file]);
68
        $writer->insertAll($query->fetch());
69
        return $this->file;
70
    }
71
72
    /**
73
     * Sets a default format to use
74
     */
75
    private function setDefaultFormat()
76
    {
77
        $this->format = $this->getBuilder()->build(
78
            JsonFormat::class,
79
            [JsonFormat::OPTION_FILE_TYPE => JsonFormat::JSON_FILE_TYPE_EACH_LINE]
80
        );
81
        if ($this->file instanceof FormatAwareInterface) {
82
            $this->file->setFormat($this->format);
83
        }
84
    }
85
}
86