LazyRecord\Importer\CSVImporter::importResource PHP Method

importResource() public method

array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] ).
public importResource ( $fd, $unsetPrimaryKey = false )
    public function importResource($fd, $unsetPrimaryKey = false)
    {
        $schema = $this->model->getSchema();
        if ($this->columnMap) {
            $columnNames = $this->columnMap;
        } else {
            $columnNames = fgetcsv($fd);
        }
        while (($fields = fgetcsv($fd)) !== false) {
            $args = array();
            foreach ($columnNames as $idx => $columnName) {
                $columnValue = $fields[$idx];
                $args[$columnName] = $columnValue;
            }
            if ($unsetPrimaryKey) {
                if ($pk = $schema->primaryKey) {
                    unset($args[$pk]);
                }
            }
            $ret = $this->model->create($args);
        }
    }

Usage Example

 public function testCollectionExporter()
 {
     $author = new Author();
     foreach (range(1, 10) as $i) {
         $ret = $author->create(array('name' => 'Foo-' . $i, 'email' => 'foo@foo' . $i, 'identity' => 'foo' . $i, 'confirmed' => true));
         $this->assertTrue($author->confirmed, 'is true');
         $this->assertTrue($ret->success);
     }
     @mkdir('tests/tmp', 0755, true);
     $fp = fopen('tests/tmp/authors.csv', 'w');
     $exporter = new CSVExporter($fp);
     $exporter->exportCollection(new AuthorCollection());
     fclose($fp);
     $authors = new AuthorCollection();
     $authors->delete();
     $fp = fopen('tests/tmp/authors.csv', 'r');
     $importer = new CSVImporter(new Author());
     $importer->importResource($fp);
     fclose($fp);
 }