Locale   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 9
Bugs 0 Features 0
Metric Value
eloc 71
c 9
b 0
f 0
dl 0
loc 228
ccs 0
cts 97
cp 0
rs 10
wmc 30

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getAppOrDefaultLocale() 0 3 1
A getAppOrDefaultCountry() 0 3 1
A getAcceptedLanguages() 0 13 5
A defaultCountry() 0 13 3
A getCountry() 0 13 3
A default() 0 13 3
A getLocale() 0 13 3
A _getLocalesDisabled() 0 5 2
A fallback() 0 12 4
A getDefaultLanguageUser() 0 14 3
A isEnabled() 0 3 1
A canBeSave() 0 3 1
1
<?php
2
3
namespace Distilleries\Contentful\Models;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Cache;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Str;
9
10
/**
11
 * @property integer $id
12
 * @property string $label
13
 * @property string $code
14
 * @property string $locale
15
 * @property string $country
16
 * @property string $fallback_code
17
 * @property boolean $is_default
18
 * @property boolean $is_editable
19
 * @property boolean $is_publishable
20
 * @property \Illuminate\Support\Carbon $created_at
21
 * @property \Illuminate\Support\Carbon $updated_at
22
 */
23
class Locale extends Model
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    protected $table = 'locales';
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    protected $fillable = [
34
        'label',
35
        'code',
36
        'locale',
37
        'country',
38
        'fallback_code',
39
        'is_default',
40
        'is_editable',
41
        'is_publishable',
42
    ];
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    protected $casts = [
48
        'is_default' => 'boolean',
49
        'is_editable' => 'boolean',
50
        'is_publishable' => 'boolean',
51
    ];
52
53
    /**
54
     * Return default locale code.
55
     *
56
     * @return string
57
     */
58
    public static function default(): string
59
    {
60
        $default = Cache::get('locale_default');
61
62
        if ($default === null) {
63
            $default = static::select('locale')->where('is_default', '=', true)->first();
64
            $default = ! empty($default) ? $default->locale : config('contentful.default_locale');
65
66
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
67
            Cache::forever('locale_default', $default);
68
        }
69
70
        return $default;
71
    }
72
73
    /**
74
     * Return application OR Contentful space default locale.
75
     *
76
     * @return string
77
     */
78
    public static function getAppOrDefaultLocale(): string
79
    {
80
        return app()->getLocale() ?? static::default();
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
        return app()->/** @scrutinizer ignore-call */ getLocale() ?? static::default();
Loading history...
81
    }
82
83
    /**
84
     * Return application OR Contentful space default country.
85
     *
86
     * @param  string  $key
87
     * @return string
88
     */
89
    public static function getAppOrDefaultCountry($key = 'app.country'): string
90
    {
91
        return config($key, static::defaultCountry());
92
    }
93
94
    /**
95
     * Return default country code.
96
     *
97
     * @return string
98
     */
99
    public static function defaultCountry(): string
100
    {
101
        $default = Cache::get('country_default');
102
103
        if ($default === null) {
104
            $default = static::select('country')->where('is_default', '=', true)->first();
105
            $default = ! empty($default) ? $default->country : config('contentful.default_country');
106
107
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
108
            Cache::forever('country_default', $default);
109
        }
110
111
        return $default;
112
    }
113
114
    /**
115
     * Return fallback code for given locale code.
116
     *
117
     * @param  string  $code
118
     * @return string
119
     */
120
    public static function fallback(string $code): string
121
    {
122
        $fallback = Cache::get('locale_fallback_' . $code);
123
124
        if ($fallback === null) {
125
            $locale = static::select('fallback_code')->where('code', '=', $code)->first();
126
            $fallback = (! empty($locale) && ! empty($locale->fallback_code)) ? $locale->fallback_code : '';
127
128
            Cache::put('locale_fallback_' . $code, $fallback, 5);
129
        }
130
131
        return $fallback;
132
    }
133
134
    /**
135
     * Return if locale can be saved.
136
     *
137
     * @param  string  $country
138
     * @param  string  $locale
139
     * @return bool
140
     */
141
    public static function canBeSave(string $country, string $locale): bool
142
    {
143
        return ! in_array($country . '_' . $locale, static::_getLocalesDisabled());
144
    }
145
146
    /**
147
     * Return disabled locales (for flatten).
148
     *
149
     * @return array
150
     */
151
    protected static function _getLocalesDisabled(): array
152
    {
153
        $locales =config('contentful.use_preview')?config('contentful.locales_not_flatten_preview', ''):config('contentful.locales_not_flatten', '');
154
155
        return explode(',', $locales);
156
    }
157
158
    /**
159
     * Check if current instance is enabled (for flatten).
160
     *
161
     * @return boolean
162
     */
163
    public function isEnabled(): bool
164
    {
165
        return ! in_array($this->country . '_' . $this->locale, static::_getLocalesDisabled());
166
    }
167
168
    /**
169
     * Return locale from ISO code.
170
     *
171
     * @param  string  $code
172
     * @return string
173
     */
174
    public static function getLocale(string $code): string
175
    {
176
        if (Str::contains($code, '_')) {
177
            $tab = explode('_', $code);
178
179
            return Str::lower($tab[0]);
180
        } elseif (Str::contains($code, '-')) {
181
            $tab = explode('-', $code);
182
183
            return Str::lower($tab[0]);
184
        }
185
186
        return Str::lower($code);
187
    }
188
189
    /**
190
     * Return country from ISO code.
191
     *
192
     * @param  string  $code
193
     * @return string
194
     */
195
    public static function getCountry(string $code): string
196
    {
197
        if (Str::contains($code, '_')) {
198
            $tab = explode('_', $code);
199
200
            return Str::lower($tab[1]);
201
        } elseif (Str::contains($code, '-')) {
202
            $tab = explode('-', $code);
203
204
            return Str::lower($tab[1]);
205
        }
206
207
        return config('contentful.default_country');
208
    }
209
210
    /**
211
     * Return request accepted languages.
212
     *
213
     * @param  \Illuminate\Http\Request|null  $request
214
     * @return string|array
215
     */
216
    public static function getAcceptedLanguages(Request $request = null)
217
    {
218
        $request = ! empty($request) ? $request : request();
219
220
        $languages = $request->server('HTTP_ACCEPT_LANGUAGE');
221
        if (! empty($languages)) {
222
            preg_match_all('/(\W|^)([a-z]{2})([^a-z]|$)/six', $languages, $locales, PREG_PATTERN_ORDER);
0 ignored issues
show
Unused Code introduced by
The call to preg_match_all() has too many arguments starting with Distilleries\Contentful\Models\PREG_PATTERN_ORDER. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

222
            /** @scrutinizer ignore-call */ 
223
            preg_match_all('/(\W|^)([a-z]{2})([^a-z]|$)/six', $languages, $locales, PREG_PATTERN_ORDER);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
223
            if (! empty($locales) && ! empty($locales[2])) {
224
                return $locales[2];
225
            }
226
        }
227
228
        return [];
229
    }
230
231
    /**
232
     * Return user default language.
233
     *
234
     * @param  \Illuminate\Http\Request|null  $request
235
     * @return string
236
     */
237
    public static function getDefaultLanguageUser(Request $request = null): string
238
    {
239
        $country = static::defaultCountry();
240
        $locales = static::getAcceptedLanguages($request);
241
        $locale = ! empty($locales) ? $locales[0] : config('app.fallback_locale');
242
243
        $localeModel = (new static)
244
            ->where('country', $country)
245
            ->where('locale', $locale)
246
            ->take(1)
247
            ->get()
248
            ->first();
249
250
        return empty($localeModel) ? static::default() : $localeModel->locale;
251
    }
252
}
253