Completed
Push — master ( 16ebaa...6f97b8 )
by Enrico
01:49
created

SimpleCsvGateway::factory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
namespace BOTK;
3
4
/**
5
 * just a simple example class to integrate FactsFactory and a Data Model
6
 */
7
class SimpleCsvGateway 
8
{
9
	
10
	protected $options;
11
	protected $factsFactory;
12
	protected $currentRow = 0;
13
	
14
	
15
	public static function factory(array $options)
16
	{
17
		return new static($options);
18
	}
19
	
20
	
21
	public function __construct(array $options)
22
	{
23
		$defaults = array(
24
			'factsProfile'		=> array(),
25
			'missingFactsIsError' => true, // if a missing fact must considered an error
26
			'bufferSize' 		=> 2000,
27
			'skippFirstLine'	=> true,
28
			'fieldDelimiter' 	=> ',',
29
		    'silent'            => false,
30
		);
31
		$this->options = array_merge($defaults,$options);
32
		$this->factsFactory = new \BOTK\FactsFactory($options['factsProfile']);
33
	}
34
	
35
	
36
	protected function readRawData()
37
	{
38
		$this->currentRow++;
39
		return fgetcsv(STDIN, $this->options['bufferSize'], $this->options['fieldDelimiter']);
40
	}
41
	
42
	protected function message($message)
43
	{
44
	    if (!$this->options['silent']){
45
	        echo $message;
46
	    }
47
	}
48
	
49
	
50
	public function run()
51
	{
52
		echo $this->factsFactory->generateLinkedDataHeader();
53
	
54
	    while ($rawdata = $this->readRawData()) {
55
	    	if($this->currentRow==1 && $this->options['skippFirstLine']){
56
	    	    $this->message ("# Header skipped\n");
57
	    		continue;
58
			}
59
    		try {
60
    			$facts =$this->factsFactory->factualize($rawdata);
61
	    		echo $facts->asTurtleFragment(), "\n";
62
				$droppedFields = $facts->getDroppedFields();
63
		    	if(!empty($droppedFields) && $this->options['missingFactsIsError']) {
64
		    	    $this->message ("\n# WARNING MISSING FACT on row {$this->currentRow}: dropped ".implode(",", $droppedFields)."\n");
65
					$this->factsFactory->addToCounter('error');
66
				}	    
67
			} catch (\BOTK\Exception\Warning $e) {
68
			    $this->message ("\n# WARNING on row {$this->currentRow}: ".$e->getMessage()."\n");
69
			} 
70
	    }
71
		
72
		echo $this->factsFactory->generateLinkedDataFooter();		
73
	}
74
}
75