Skip to content

Commit

Permalink
add a SQL Observer
Browse files Browse the repository at this point in the history
  • Loading branch information
Mori Reo committed Dec 5, 2012
1 parent 70d56f0 commit 0f1adb6
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/Goodby/CSV/Import/Standard/Observer/SqlObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Goodby\CSV\Import\Standard\Observer;

class SqlObserver
{
private $table;
private $columns;
private $path;

private $file = null;

public function __construct($table, $columns, $path)
{
$this->table = $table;
$this->columns = $columns;
$this->path = $path;
}

public function notify($line)
{
$sql = $this->buildSql($line);

if ($this->file === null) {
$this->file = new \SplFileObject($this->path, 'a');
}

$this->file->fwrite($sql);
}

private function buildSql($line)
{
$line = array_map(function($value) {
$number = filter_var($value, FILTER_VALIDATE_INT);

if ($number !== false) {
return $number;
}

if (is_string($value)) {
if (strtolower($value) === 'null') {
return 'NULL';
}

if (strtolower($value) === 'true') {
return 'true';
}

if (strtolower($value) === 'false') {
return 'false';
}

return '"' . addslashes($value) . '"';
}
}, $line);

return 'INSERT INTO ' . $this->table . '(' . join(', ', $this->columns) . ')' .
' VALUES(' . join(', ', $line) . ');';
}
}
34 changes: 34 additions & 0 deletions src/Goodby/CSV/Import/Tests/Standard/Observer/SqlObserverTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Goodby\CSV\Import\Tests\Standard\Observer;

use Mockery as m;

use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\Observer\SqlObserver;

/**
* unit test for sql observer
*/
class SqlObserverTest extends \PHPUnit_Framework_TestCase
{
public function testUsage()
{
$interpreter = new Interpreter();

$tempDir = sys_get_temp_dir();

$path = $tempDir . DIRECTORY_SEPARATOR . 'test.sql';
unlink($path);

$sqlObserver = new SqlObserver('test', array('id', 'name', 'age', 'flag', 'flag2', 'status', 'contents'), $path);

$interpreter->addObserver(array($sqlObserver, 'notify'));

$interpreter->interpret(array('123', 'test', '28', 'true', 'false', 'null', 'test"test'));

$expectedSql = 'INSERT INTO test(id, name, age, flag, flag2, status, contents) VALUES(123, "test", 28, true, false, NULL, "test\"test");';

$this->assertEquals($expectedSql, file_get_contents($path));
}
}

0 comments on commit 0f1adb6

Please sign in to comment.