Passed
Push — master ( a535f0...f38dcf )
by Jean Paul
08:30
created

DatabaseExtractor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 26
dl 0
loc 67
rs 10
c 2
b 0
f 0
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setQuery() 0 3 1
A extract() 0 27 6
A getQuery() 0 3 1
A getArrayRepresentation() 0 13 1
A __construct() 0 3 1
1
<?php
2
3
namespace Coco\SourceWatcher\Core\Extractors;
4
5
use Coco\SourceWatcher\Core\Extractor;
6
use Coco\SourceWatcher\Core\IO\Inputs\DatabaseInput;
7
use Coco\SourceWatcher\Core\Row;
8
use Coco\SourceWatcher\Core\SourceWatcherException;
9
10
/**
11
 * Class DatabaseExtractor
12
 *
13
 * @package Coco\SourceWatcher\Core\Extractors
14
 */
15
class DatabaseExtractor extends Extractor
16
{
17
    protected string $query;
18
19
    protected array $availableOptions = [ "query" ];
20
21
    public function __construct ()
22
    {
23
        $this->query = "";
24
    }
25
26
    public function getQuery () : string
27
    {
28
        return $this->query;
29
    }
30
31
    public function setQuery ( string $query ) : void
32
    {
33
        $this->query = $query;
34
    }
35
36
    /**
37
     * @return array
38
     * @throws SourceWatcherException
39
     */
40
    public function extract () : array
41
    {
42
        if ( $this->input == null ) {
43
            throw new SourceWatcherException( "An input must be provided" );
44
        }
45
46
        if ( !( $this->input instanceof DatabaseInput ) ) {
47
            throw new SourceWatcherException( sprintf( "The input must be an instance of %s", DatabaseInput::class ) );
48
        }
49
50
        if ( $this->input->getInput() == null ) {
51
            throw new SourceWatcherException( "No database connector found. Set a connector before trying to extract from the database" );
52
        }
53
54
        if ( $this->query == null ) {
55
            throw new SourceWatcherException( "Query missing" );
56
        }
57
58
        $result = [];
59
60
        $arrayResults = $this->input->getInput()->executePlainQuery( $this->query );
61
62
        foreach ( $arrayResults as $currentRecord ) {
63
            array_push( $result, new Row( $currentRecord ) );
64
        }
65
66
        return $result;
67
    }
68
69
    public function getArrayRepresentation () : array
70
    {
71
        $result = parent::getArrayRepresentation();
72
73
        $dbInput = $this->getInput();
74
        $dbConnector = $dbInput->getInput();
75
76
        $result["input"] = [
77
            "class" => get_class( $dbConnector ),
78
            "parameters" => $dbConnector->getConnectionParameters()
79
        ];
80
81
        return $result;
82
    }
83
}
84