Last active
December 13, 2015 16:48
-
-
Save jimbojsb/4942515 to your computer and use it in GitHub Desktop.
Parse behat data tables into mongo documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @Given /^existing "([^"]*)" with data:$/ | |
*/ | |
public function existingWithData($arg1, TableNode $table) | |
{ | |
$collection = $arg1; | |
foreach ($table->getHash() as $row) { | |
$data = array(); | |
foreach ($row as $key => $value) { | |
if (strpos($key, "[]") !== false) { | |
$key = str_replace("[]", "", $key); | |
$data[$key] = explode(',', $value); | |
} else if (strpos($key, ".") !== false) { | |
$keyParts = array_reverse(explode('.', $key)); | |
$tempData = []; | |
for ($c = 0; $c < count($keyParts); $c++) { | |
if ($c == count($keyParts) - 1) { | |
if (isset($data[$keyParts[$c]])) { | |
$data[$keyParts[$c]] = array_merge_recursive($data[$keyParts[$c]], $tempData); | |
} else { | |
$data[$keyParts[$c]] = $tempData; | |
} | |
} else if ($c == 0) { | |
$tempData = [$keyParts[$c] => $value]; | |
} else { | |
$tempData = [$keyParts[$c] => $tempData]; | |
} | |
} | |
} else { | |
$data[$key] = $value; | |
} | |
} | |
self::$mongo->test->$collection->insert($data); | |
} | |
} | |
Parses data like: | |
| buy_url | tags[] | type | origin.name | origin.url | | |
| http://www.google.com/ | testtag1,testtag2 | deal | Test Tag 1 | testtag1 | | |
into valid mongo documents like: | |
{ | |
"buy_url" : "http://www.google.com/", | |
"tags" : [ "testtag1", "testtag2" ], | |
"type" : "deal", | |
"origin" : { | |
"name" : "Test Tag 1", | |
"url" : "testtag1" | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment