Completed
Push — master ( 825d81...9c7056 )
by Maxime
08:49
created

ContentfulModel::scopeLocale()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 3
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 12
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Distilleries\Contentful\Models\Base;
4
5
use Distilleries\Contentful\Models\EntryRelationship;
6
use Distilleries\Contentful\Models\Traits\Localable;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Model;
9
use Distilleries\Contentful\Models\Asset;
10
11
abstract class ContentfulModel extends Model
12
{
13
    use Localable;
14
15
    /**
16
     * {@inheritdoc}
17
     */
18
    protected $primaryKey = 'contentful_id';
19
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    protected $keyType = 'string';
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public $incrementing = false;
30
31
    /**
32
     * ContentfulModel constructor.
33
     *
34
     * @param  array  $attributes
35
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
36
     */
37
    public function __construct(array $attributes = [])
38
    {
39
        // Override fillable
40
        foreach ($this->defaultFillable() as $defaultFillable) {
41
            if (! in_array($defaultFillable, $this->fillable)) {
42
                $this->fillable[] = $defaultFillable;
43
            }
44
        }
45
46
        // Override casts
47
        foreach ($this->defaultCasts() as $field => $type) {
48
            if (! isset($this->casts[$field])) {
49
                $this->casts[$field] = $type;
50
            }
51
        }
52
53
        parent::__construct($attributes);
54
    }
55
56
    /**
57
     * Return default fillable fields.
58
     *
59
     * @return array
60
     */
61
    public function defaultFillable() : array
62
    {
63
        return [
64
            'contentful_id',
65
            'country',
66
            'locale',
67
            'payload',
68
            'created_at',
69
            'updated_at',
70
        ];
71
    }
72
73
    /**
74
     * Return default casted fields.
75
     *
76
     * @return array
77
     */
78
    public function defaultCasts() : array
79
    {
80
        return [
81
            'payload' => 'array',
82
        ];
83
    }
84
85
86
    // --------------------------------------------------------------------------------
87
    // --------------------------------------------------------------------------------
88
    // --------------------------------------------------------------------------------
89
90
    /**
91
     * Return Contentful Asset for given link (sys or ID).
92
     *
93
     * @param  array|string|null  $link
94
     * @return \Distilleries\Contentful\Models\Asset|null
95
     */
96
    protected function contentfulAsset($link) : ?Asset
97
    {
98
        $assetId = $this->contentfulLinkId($link);
99
100
        if (empty($assetId)) {
101
            return null;
102
        }
103
104
        $asset = (new Asset)->query()
105
            ->where('contentful_id', '=', $assetId)
106
            ->where('locale', '=', $this->locale)
107
            ->where('country', '=', $this->country)
108
            ->first();
109
110
        return ! empty($asset) ? $asset : null;
111
    }
112
113
    /**
114
     * Return Contentful Entry for given link (sys or ID).
115
     *
116
     * @param  array|string|null  $link
117
     * @return \Distilleries\Contentful\Models\Base\ContentfulModel|null
118
     */
119
    protected function contentfulEntry($link) : ?ContentfulModel
120
    {
121
        $entryId = $this->contentfulLinkId($link);
122
123
        if (empty($entryId)) {
124
            return null;
125
        }
126
127
        $entries = $this->contentfulEntries([$entryId]);
128
129
        return $entries->isNotEmpty() ? $entries->first() : null;
130
    }
131
132
    /**
133
     * Return Contentful Entries for given ID.
134
     *
135
     * @param  array  $links
136
     * @return \Illuminate\Support\Collection
137
     */
138
    protected function contentfulEntries(array $links) : Collection
139
    {
140
        $entries = [];
141
142
        $entryIds = [];
143
        foreach ($links as $link) {
144
            $entryId = $this->contentfulLinkId($link);
145
            if (! empty($entryId)) {
146
                $entryIds[] = $entryId;
147
            }
148
        }
149
150
        if (! empty($entryIds)) {
151
            $relationships = EntryRelationship::query()
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
152
                ->select('related_contentful_id', 'related_contentful_type')
153
                ->distinct()
154
                ->locale($this->locale,$this->country)
155
                ->where('source_contentful_id', '=', $this->contentful_id)
156
                ->whereIn('related_contentful_id', $entryIds)
157
                ->orderBy('order', 'asc')
158
                ->get();
159
160
            foreach ($relationships as $relationship) {
161
                if ($relationship->related_contentful_type === 'asset') {
162
                    $model = new Asset;
163
                } else {
164
                    $modelClass = '\App\Models\\' . studly_case($relationship->related_contentful_type);
165
                    $model = new $modelClass;
166
                }
167
168
                $instance = $model->query()
169
                    ->where('country', '=', $this->country)
170
                    ->where('locale', '=', $this->locale)
171
                    ->where('contentful_id', '=', $relationship->related_contentful_id)
172
                    ->first();
173
174
                if (! empty($instance)) {
175
                    $entries[] = $instance;
176
                }
177
            }
178
        }
179
180
        return collect($entries);
181
    }
182
183
    /**
184
     * Return a collection of related models for base Contentful ID.
185
     *
186
     * @param  string  $contentfulId
187
     * @param  string  $contentfulType
188
     * @return \Illuminate\Support\Collection
189
     */
190
    protected function contentfulRelatedEntries(string $contentfulId, string $contentfulType = '') : Collection
191
    {
192
        $entries = [];
193
194
        $query = EntryRelationship::query()
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
195
            ->select('source_contentful_id', 'source_contentful_type')
196
            ->locale($this->locale,$this->country)
197
            ->where('related_contentful_id', '=', $contentfulId);
198
199
        if (! empty($contentfulType)) {
200
            $query = $query->where('source_contentful_type', '=', $contentfulType);
201
        }
202
203
        $relationships = $query->orderBy('order', 'asc')->get();
204
        foreach ($relationships as $relationship) {
205
            if ($relationship->source_contentful_type === 'asset') {
206
                $model = new Asset;
207
            } else {
208
                $modelClass = rtrim(config('contentful.namespace.model'),'\\') .'\\' . studly_case($relationship->source_contentful_type);
209
                $model = new $modelClass;
210
            }
211
212
            $instance = $model->query()
213
                ->locale($this->locale,$this->country)
214
                ->where('contentful_id', '=', $relationship->source_contentful_id)
215
                ->first();
216
217
            if (! empty($instance)) {
218
                $entries[] = $instance;
219
            }
220
        }
221
222
        return collect($entries);
223
    }
224
225
    /**
226
     * Return Contentful link ID.
227
     *
228
     * @param  mixed  $link
229
     * @return string|null
230
     */
231
    protected function contentfulLinkId($link) : ?string
232
    {
233
        if (empty($link)) {
234
            return null;
235
        }
236
237
        if (is_string($link)) {
238
            return $link;
239
        }
240
241
        if (is_array($link) and isset($link['sys']) and isset($link['sys']['id'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
242
            return $link['sys']['id'];
243
        }
244
245
        return null;
246
    }
247
}
248