Completed
Push — 1.0.0-alpha ( c04b09...2436c2 )
by Alex
11s
created

JsonApiSerializer::setBaseUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Huntie\JsonApi\Serializers;
4
5
use JsonSerializable;
6
use Request;
7
8
abstract class JsonApiSerializer implements JsonSerializable
9
{
10
    /**
11
     * The JSON API version being implemented.
12
     *
13
     * @var string
14
     */
15
    const JSON_API_VERSION = '1.0';
16
17
    /**
18
     * The base URL for links.
19
     *
20
     * @var string
21
     */
22
    protected $baseUrl;
23
24
    /**
25
     * Meta information to include.
26
     *
27
     * @var array
28
     */
29
    protected $meta = [];
30
31
    /**
32
     * Resource links to include, relative to the base URL.
33
     *
34
     * @var array
35
     */
36
    protected $links = [];
37
38
    /**
39
     * Create a new JSON API document serializer.
40
     */
41
    public function __construct()
42
    {
43
        $this->baseUrl = Request::url();
44
        $this->addLinks('self', urldecode(str_replace(Request::url(), '', Request::fullUrl())));
45
    }
46
47
    /**
48
     * Return primary data for the JSON API document.
49
     *
50
     * @return mixed
51
     */
52
    abstract protected function getPrimaryData();
53
54
    /**
55
     * Return any links related to the primary data.
56
     */
57
    public function getLinks(): array
58
    {
59
        return array_map(function ($path) {
60
            return $this->baseUrl . $path;
61
        }, $this->links);
62
    }
63
64
    /**
65
     * Return any secondary included resource objects.
66
     *
67
     * @return \Illuminate\Support\Collection
68
     */
69
    public function getIncluded()
70
    {
71
        return collect();
72
    }
73
74
    /**
75
     * Set the base URL for document links.
76
     *
77
     * @param string $url
78
     */
79
    public function setBaseUrl(string $url)
80
    {
81
        $this->baseUrl = preg_replace('/\/$/', '', $url);
82
    }
83
84
    /**
85
     * Add included meta information.
86
     *
87
     * @param string|array    $key
88
     * @param string|int|null $value
89
     */
90
    public function addMeta($key, $value = null)
91
    {
92
        $this->meta = array_merge($this->meta, is_array($key) ? $key : [$key => $value]);
93
    }
94
95
    /**
96
     * Add one or more included links.
97
     *
98
     * @param string|array    $key
99
     * @param string|int|null $value
100
     */
101
    public function addLinks($key, $value = null)
102
    {
103
        $this->links = array_merge($this->links, is_array($key) ? $key : [$key => $value]);
104
    }
105
106
    /**
107
     * Serialise JSON API document to an array.
108
     */
109
    public function serializeToObject(): array
110
    {
111
        return array_merge(
112
            ['data' => $this->getPrimaryData()],
113
            array_filter([
114
                'included' => $this->getIncluded()->values()->toArray(),
115
                'links' => $this->getLinks(),
116
                'meta' => $this->meta,
117
                'jsonapi' => $this->getDocumentMeta(),
118
            ])
119
        );
120
    }
121
122
    /**
123
     * Convert the object into something JSON serializable.
124
     */
125
    public function jsonSerialize(): array
126
    {
127
        return $this->serializeToObject();
128
    }
129
130
    /**
131
     * Serialise JSON API document to a JSON string.
132
     */
133
    public function serializeToJson(): string
134
    {
135
        return json_encode($this->jsonSerialize());
136
    }
137
138
    /**
139
     * Reduce a collection of records to unique entries, by comparing their
140
     * resource identifier values.
141
     *
142
     * @param \Illuminate\Support\Collection $records
143
     *
144
     * @return \Illuminate\Support\Collection
145
     */
146
    protected function filterUnique($records)
147
    {
148
        return $records->unique(function ($record) {
149
            return implode(array_only($record, ['type', 'id']));
150
        });
151
    }
152
153
    /**
154
     * Return JSON API implementation information.
155
     */
156
    private function getDocumentMeta(): array
157
    {
158
        return array_filter([
159
            'version' => config('jsonapi.include_version') ? self::JSON_API_VERSION : null,
160
        ]);
161
    }
162
}
163