Skip to content

Commit

Permalink
Add support for non array accessible classes by using collect + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
LarsGrevelink committed Feb 8, 2020
1 parent 2463953 commit e326d2f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Laracsv/Export.php
Expand Up @@ -139,6 +139,10 @@ private function addCsvRows(Collection $collection, array $fields, Writer $csv)
}
}

if (!Arr::accessible($model)) {
$model = collect($model);
}

$csvRow = [];
foreach ($fields as $field) {
$csvRow[] = Arr::get($model, $field);
Expand Down
34 changes: 34 additions & 0 deletions tests/Laracsv/ExportTest.php
Expand Up @@ -5,6 +5,7 @@
use Laracsv\Models\Category;
use Laracsv\Models\Product;
use League\Csv\Writer;
use stdClass;

class ExportTest extends TestCase
{
Expand Down Expand Up @@ -159,6 +160,39 @@ public function testIlluminateSupportCollection()
$this->assertSame('4', $fourthLine[0]);
}

public function testExportPlainObjects()
{
$faker = \Faker\Factory::create();

$csvExporter = new Export();

$data = [];
for ($i = 1; $i < 5; $i++) {
$object = new stdClass();
$object->id = $i;
$object->address = $faker->streetAddress;
$object->firstName = $faker->firstName;

$data[] = $object;
}

$data = collect($data);

$csvExporter->build($data, [
'id',
'firstName',
'address'
]);

$csv = trim($csvExporter->getWriter()->getContent());

$lines = explode(PHP_EOL, $csv);
$fourthLine = explode(',', $lines[4]);

$this->assertCount(5, $lines);
$this->assertSame('4', $fourthLine[0]);
}

public function testRead()
{
$products = Product::limit(10)->get();
Expand Down

0 comments on commit e326d2f

Please sign in to comment.