From f101fe830e87c627be3ebaf42c863991ed81fa41 Mon Sep 17 00:00:00 2001 From: Sander de Vos Date: Sun, 29 Jul 2018 16:26:51 +0200 Subject: [PATCH] Resolves #16 --- readme.md | 5 ++-- src/Contracts/Portable.php | 20 ++++++++++++++ src/Portable.php | 54 +++++++++++++++++++++++++++++++++++++- 3 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 src/Contracts/Portable.php diff --git a/readme.md b/readme.md index 70dfa40..ec82444 100644 --- a/readme.md +++ b/readme.md @@ -26,7 +26,7 @@ After installing the package, you should publish the configuration file: $ php artisan vendor:publish --tag=gdpr-config ``` -Finally, add the `Soved\Laravel\Gdpr\Portable` trait to the `App\User` model: +Finally, add the `Soved\Laravel\Gdpr\Portable` trait to the `App\User` model and implement the `Soved\Laravel\Gdpr\Contracts\Portable` contract: ```php gdprWith)) { - $this->loadMissing($this->gdprWith); + $this->loadRelations($this->gdprWith); } // Make the given attributes visible @@ -29,6 +31,56 @@ public function portable() return $this->toPortableArray(); } + /** + * Eager load the given relations. + * + * @param array $relations + * @return void + */ + public function loadRelations(array $relations) + { + $portableRelations = $this->getPortableRelations($relations); + + array_walk($portableRelations, [$this, 'loadPortableRelation']); + + $this->load(array_diff($relations, $portableRelations)); + } + + /** + * Get all portable relations. + * + * @param array $relations + * @return array + */ + private function getPortableRelations(array $relations) + { + $portableRelations = []; + + foreach ($relations as $relation) { + if ($this->$relation()->getRelated() instanceof PortableContract) { + $portableRelations[] = $relation; + } + } + + return $portableRelations; + } + + /** + * Load and transform a portable relation. + * + * @param string $relation + * @return void + */ + private function loadPortableRelation(string $relation) + { + $this->attributes[$relation] = $this + ->$relation() + ->get() + ->transform(function ($item) { + return $item->portable(); + }); + } + /** * Get the GDPR compliant data portability array for the model. *