Passed
Push — serialization-refactor ( cf9a88...e80911 )
by Alex
06:22
created

JsonApiSerializer::getPrimaryData()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 1
nc 1
1
<?php
2
3
namespace Huntie\JsonApi\Serializers;
4
5
abstract class JsonApiSerializer
6
{
7
    /**
8
     * Meta information to include.
9
     *
10
     * @var \Illuminate\Support\Collection
11
     */
12
    protected $meta;
13
14
    /**
15
     * Resource links to include.
16
     *
17
     * @var \Illuminate\Support\Collection
18
     */
19
    protected $links;
20
21
    /**
22
     * Create a new JSON API document serializer.
23
     */
24
    public function __construct()
25
    {
26
        $this->meta = collect([]);
27
        $this->links = collect([]);
28
    }
29
30
    /**
31
     * Return primary data for the JSON API document.
32
     *
33
     * @return array
34
     */
35
    abstract protected function getPrimaryData();
36
37
    /**
38
     * Add included meta information.
39
     *
40
     * @param string|array    $key
41
     * @param string|int|null $value
42
     */
43
    public function addMeta($key, $value = null)
44
    {
45
        $this->meta = $this->meta->merge(is_array($key) ? $key : [$key => $value]);
46
    }
47
48
    /**
49
     * Add one or more included links.
50
     *
51
     * @param string|array    $key
52
     * @param string|int|null $value
53
     */
54
    public function addLinks($key, $value = null)
55
    {
56
        $this->links = $this->links->merge(is_array($key) ? $key : [$key => $value]);
57
    }
58
59
    /**
60
     * Serialise JSON API document to an array.
61
     *
62
     * @return array
63
     */
64
    public function serializeToObject()
65
    {
66
        return array_filter([
67
            'data' => $this->getPrimaryData(),
68
            'links' => $this->links->toArray(),
69
            'meta' => $this->meta->toArray(),
70
        ]);
71
    }
72
73
    /**
74
     * Serialise JSON API document to a JSON string.
75
     *
76
     * @return array
77
     */
78
    public function serializeToJson()
79
    {
80
        return json_encode($this->serializeToObject());
81
    }
82
}
83