1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MathieuTu\JsonSyncer\Helpers; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOne; |
6
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOneOrMany; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
use MathieuTu\JsonSyncer\Contracts\JsonExportable; |
9
|
|
|
|
10
|
|
|
class JsonExporter |
11
|
|
|
{ |
12
|
|
|
private $exportable; |
13
|
|
|
|
14
|
3 |
|
public function __construct(JsonExportable $exportable) |
15
|
|
|
{ |
16
|
3 |
|
$this->exportable = $exportable; |
17
|
3 |
|
} |
18
|
|
|
|
19
|
2 |
|
public static function exportToJson(JsonExportable $exportable, $options = 0) |
20
|
|
|
{ |
21
|
2 |
|
return self::exportToCollection($exportable)->toJson($options); |
22
|
|
|
} |
23
|
|
|
|
24
|
3 |
|
public static function exportToCollection(JsonExportable $exportable): Collection |
25
|
|
|
{ |
26
|
3 |
|
$helper = new static($exportable); |
27
|
|
|
|
28
|
3 |
|
return $helper->exportAttributes()->merge($helper->exportRelations()); |
29
|
|
|
} |
30
|
|
|
|
31
|
3 |
|
public function exportAttributes(): Collection |
32
|
|
|
{ |
33
|
3 |
|
return collect($this->exportable->getJsonExportableAttributes()) |
34
|
3 |
|
->mapWithKeys(function ($attribute) { |
35
|
3 |
|
return [$attribute => $this->exportable->$attribute]; |
36
|
3 |
|
}); |
37
|
|
|
} |
38
|
|
|
|
39
|
2 |
|
public function exportRelations(): Collection |
40
|
|
|
{ |
41
|
2 |
|
return collect($this->exportable->getJsonExportableRelations()) |
42
|
2 |
|
->mapWithKeys(function ($relationName) { |
43
|
2 |
|
return [$relationName => $this->exportable->$relationName()]; |
44
|
|
|
})->filter(function ($relationObject) { |
45
|
2 |
|
return $relationObject instanceof HasOneOrMany |
46
|
2 |
|
&& $relationObject->getRelated() instanceof JsonExportable; |
47
|
|
|
})->map(function (HasOneOrMany $relationObject) { |
48
|
2 |
|
$export = $relationObject->get()->map(function ($object) { |
49
|
2 |
|
return self::exportToCollection($object); |
50
|
2 |
|
}); |
51
|
|
|
|
52
|
|
|
return $relationObject instanceof HasOne ? $export->first() : $export; |
53
|
|
|
}); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|