ENHANCEMENT Added support for custom importer methods in CsvBulkLoader

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.3@66045 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Ingo Schommer 2008-11-17 18:44:11 +00:00 committed by Sam Minnee
parent 5df7e70cf8
commit f4d0fec83b
2 changed files with 27 additions and 5 deletions

View File

@ -44,7 +44,7 @@ class CsvBulkLoader extends BulkLoader {
}
foreach($csv as $row) {
$this->processRecord($row, array(), $results, $preview);
$this->processRecord($row, $this->columnMap, $results, $preview);
}
return $results;
@ -100,8 +100,10 @@ class CsvBulkLoader extends BulkLoader {
// second run: save data
foreach($record as $fieldName => $val) {
if($this->isNullValue($val, $fieldName)) continue;
if($obj->hasMethod("import{$fieldName}")) {
if(strpos($fieldName, '->') !== FALSE) {
$funcName = substr($fieldName, 2);
$this->$funcName($obj, $val, $record);
} else if($obj->hasMethod("import{$fieldName}")) {
$obj->{"import{$fieldName}"}($val, $record);
} else {
$obj->update(array($fieldName => $val));

View File

@ -136,6 +136,20 @@ class CsvBulkLoaderTest extends SapphireTest {
}
function testLoadWithCustomImportMethods() {
$loader = new CsvBulkLoaderTest_CustomLoader('CsvBulkLoaderTest_Player');
$filepath = Director::baseFolder() . '/sapphire/tests/dev/CsvBulkLoaderTest_PlayersWithHeader.csv';
$loader->columnMap = array(
'FirstName' => '->importFirstName',
'Biography' => 'Biography',
'Birthday' => 'Birthday'
);
$results = $loader->load($filepath);
$player = DataObject::get_by_id('CsvBulkLoaderTest_Player', 1);
$this->assertEquals($player->FirstName, 'Customized John');
$this->assertEquals($player->Biography, "He's a good guy");
}
protected function getLineCount(&$file) {
$i = 0;
while(fgets($file) !== false) $i++;
@ -145,6 +159,12 @@ class CsvBulkLoaderTest extends SapphireTest {
}
class CsvBulkLoaderTest_CustomLoader extends CsvBulkLoader implements TestOnly {
function importFirstName(&$obj, $val, $record) {
$obj->FirstName = "Customized {$val}";
}
}
class CsvBulkLoaderTest_Team extends DataObject implements TestOnly {
static $db = array(
@ -184,7 +204,7 @@ class CsvBulkLoaderTest_Player extends DataObject implements TestOnly {
* @param string $val
* @param array $record
*/
public function setUSBirthday($val, $record) {
public function setUSBirthday($val, $record = null) {
$this->Birthday = preg_replace('/^([0-9]{1,2})\/([0-9]{1,2})\/([0-90-9]{2,4})/', '\\3-\\1-\\2', $val);
}
}