Skip to content

Commit

Permalink
✨ Add exportToCollection() to the JsonExportable.
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieutu committed Aug 7, 2017
1 parent 8dcdf6a commit 8328a2e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/Contracts/JsonExportable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

namespace MathieuTu\JsonSyncer\Contracts;

use Illuminate\Support\Collection;

interface JsonExportable
{
public function getJsonExportableAttributes(): array;

public function getJsonExportableRelations(): array;

public function exportToJson($jsonOptions = 0): string;

public function exportToCollection(): Collection;
}
6 changes: 6 additions & 0 deletions src/Traits/JsonExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MathieuTu\JsonSyncer\Traits;

use Illuminate\Support\Collection;
use MathieuTu\JsonSyncer\Helpers\JsonExporter as ExporterHelper;
use MathieuTu\JsonSyncer\Helpers\RelationsInModelFinder;

Expand All @@ -15,6 +16,11 @@ public function exportToJson($jsonOptions = 0): string
return ExporterHelper::exportToJson($this, $jsonOptions);
}

public function exportToCollection(): Collection
{
return ExporterHelper::exportToCollection($this);
}

public function getJsonExportableAttributes(): array
{
return $this->jsonExportableAttributes ?? array_filter($this->getFillable(), function ($attribute) {
Expand Down
25 changes: 20 additions & 5 deletions tests/JsonExporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,26 @@
class JsonExporterTest extends TestCase
{
public function testExportToJson()
{
$this->setDatabase();

$this->assertEquals(
json_decode(file_get_contents(__DIR__ . '/Stubs/import.json')),
json_decode(Foo::first()->exportToJson())
);
}

public function testExportToCollection()
{
$this->setDatabase();

$this->assertEquals(
json_decode(file_get_contents(__DIR__ . '/Stubs/import.json'), true),
Foo::first()->exportToCollection()->toArray()
);
}

protected function setDatabase()
{
(new Foo)->create(['author' => 'Mathieu TUDISCO', 'username' => '@mathieutu'])
->bars()->createMany([
Expand All @@ -21,10 +41,5 @@ public function testExportToJson()
['name' => 'do not 3'],
]);
});

$this->assertEquals(
json_decode(file_get_contents(__DIR__ . '/Stubs/import.json')),
json_decode(Foo::first()->exportToJson())
);
}
}

0 comments on commit 8328a2e

Please sign in to comment.