Passed
Push — master ( 19e483...625e7f )
by Mathieu
04:13
created

JsonExporter::exportToJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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