From 8328a2e66fcb20920e05c40e707bc42358084d52 Mon Sep 17 00:00:00 2001 From: Mathieu TUDISCO Date: Mon, 7 Aug 2017 11:11:35 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20exportToCollection()=20to=20t?= =?UTF-8?q?he=20JsonExportable.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Contracts/JsonExportable.php | 4 ++++ src/Traits/JsonExporter.php | 6 ++++++ tests/JsonExporterTest.php | 25 ++++++++++++++++++++----- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/Contracts/JsonExportable.php b/src/Contracts/JsonExportable.php index a7f0a28..6bcf1af 100644 --- a/src/Contracts/JsonExportable.php +++ b/src/Contracts/JsonExportable.php @@ -2,6 +2,8 @@ namespace MathieuTu\JsonSyncer\Contracts; +use Illuminate\Support\Collection; + interface JsonExportable { public function getJsonExportableAttributes(): array; @@ -9,4 +11,6 @@ public function getJsonExportableAttributes(): array; public function getJsonExportableRelations(): array; public function exportToJson($jsonOptions = 0): string; + + public function exportToCollection(): Collection; } diff --git a/src/Traits/JsonExporter.php b/src/Traits/JsonExporter.php index 2d73892..8e2d86d 100644 --- a/src/Traits/JsonExporter.php +++ b/src/Traits/JsonExporter.php @@ -2,6 +2,7 @@ namespace MathieuTu\JsonSyncer\Traits; +use Illuminate\Support\Collection; use MathieuTu\JsonSyncer\Helpers\JsonExporter as ExporterHelper; use MathieuTu\JsonSyncer\Helpers\RelationsInModelFinder; @@ -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) { diff --git a/tests/JsonExporterTest.php b/tests/JsonExporterTest.php index 3e77b5c..3de208e 100644 --- a/tests/JsonExporterTest.php +++ b/tests/JsonExporterTest.php @@ -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([ @@ -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()) - ); } }