JsonExporter::exportAttributes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
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 JsonExportable $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): string
20
    {
21 2
        return self::exportToCollection($exportable)->toJson($options | JSON_THROW_ON_ERROR);
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(fn($attribute) => [$attribute => $this->exportable->$attribute]);
35
    }
36
37 2
    public function exportRelations(): Collection
38
    {
39 2
        return collect($this->exportable->getJsonExportableRelations())
40 2
            ->mapWithKeys(fn($relationName) => [$relationName => $this->exportable->$relationName()])
41 2
            ->filter(fn($relationObject) => $relationObject instanceof HasOneOrMany && $relationObject->getRelated() instanceof JsonExportable)
42 2
            ->map(function (HasOneOrMany $relationObject) {
43 2
                $export = $relationObject->get()->map(fn($object) => self::exportToCollection($object));
44
45 2
                return $relationObject instanceof HasOne ? $export->first() : $export;
46 2
            });
47
    }
48
}
49