Completed
Push — master ( bd1ebd...847696 )
by Maxime
03:37
created

Locale::getAppOrDefaultLocale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Distilleries\Contentful\Models;
4
5
use Illuminate\Support\Facades\Cache;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Str;
8
9
/**
10
 * @property integer $id
11
 * @property string $label
12
 * @property string $code
13
 * @property string $fallback_code
14
 * @property boolean $is_editable
15
 * @property boolean $is_publishable
16
 * @property \Illuminate\Support\Carbon $created_at
17
 * @property \Illuminate\Support\Carbon $updated_at
18
 */
19
class Locale extends Model
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    protected $table = 'locales';
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    protected $fillable = [
30
        'label',
31
        'code',
32
        'locale',
33
        'country',
34
        'fallback_code',
35
        'is_default',
36
        'is_editable',
37
        'is_publishable',
38
    ];
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected $casts = [
44
        'is_default' => 'boolean',
45
        'is_editable' => 'boolean',
46
        'is_publishable' => 'boolean',
47
    ];
48
49
    /**
50
     * Return default locale code.
51
     *
52
     * @return string
53
     */
54 View Code Duplication
    public static function default(): string
2 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Possible parse error: non-abstract method defined as abstract
Loading history...
55
    {
56
        $default = Cache::get('locale_default');
1 ignored issue
show
Coding Style introduced by
The visibility should be declared for property $default.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
57
58
        if ($default === null)
1 ignored issue
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $default.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
59
        {
60
            $default = static::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...
61
                ->select('locale')
62
                ->where('is_default', '=', true)
63
                ->first();
64
65
            $default = !empty($default) ? $default->locale : config('contentful.default_locale');
2 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $default.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
66
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
67
            Cache::forever('locale_default', $default);
1 ignored issue
show
Coding Style introduced by
The visibility should be declared for property $default.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
68
        }
69
70
        return $default;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $default.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
71
    }
72
73
74
    public static function getAppOrDefaultLocale(): string
75
    {
76
        return app()->getLocale() ?? self::default();
77
    }
78
79
    public static function getAppOrDefaultCountry($key = 'app.country'): string
80
    {
81
        return config($key, self::defaultCountry());
82
    }
83
84
    /**
85
     * Return default country code.
86
     *
87
     * @return string
88
     */
89 View Code Duplication
    public static function defaultCountry(): string
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
    {
91
        $default = Cache::get('country_default');
92
93
        if ($default === null)
94
        {
95
            $default = static::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...
96
                ->select('country')
97
                ->where('is_default', '=', true)
98
                ->first();
99
            $default = !empty($default) ? $default->country : config('contentful.default_country');
100
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
101
            Cache::forever('country_default', $default);
102
        }
103
104
        return $default;
105
    }
106
107
    /**
108
     * Return fallback code for given locale code.
109
     *
110
     * @param  string $code
111
     * @return string
112
     */
113
    public static function fallback(string $code): string
114
    {
115
        $fallback = Cache::get('locale_fallback_' . $code);
116
117
        if ($fallback === null)
118
        {
119
            $locale = static::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...
120
                ->select('fallback_code')
121
                ->where('code', '=', $code)
122
                ->first();
123
124
            $fallback = (!empty($locale) and !empty($locale->fallback_code)) ? $locale->fallback_code : '';
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...
125
126
            Cache::put('locale_fallback_' . $code, $fallback, 5);
127
        }
128
129
        return $fallback;
130
    }
131
132
    public static function canBeSave(string $country, string $locale): bool
133
    {
134
        return !in_array($country . '_' . $locale, static::_getLocalesDisabled());
135
    }
136
137
    protected static function _getLocalesDisabled(): array
138
    {
139
        $locales = config('contentful.locales_not_flatten', '');
140
        return explode(',', $locales);
141
    }
142
143
    public function isEnabled(): bool
144
    {
145
        return !in_array($this->country . '_' . $this->locale, static::_getLocalesDisabled());
146
    }
147
148 View Code Duplication
    public static function getLocale(string $locale): string
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
    {
150
        if (Str::contains($locale, '_'))
151
        {
152
            $tab = explode('_', $locale);
153
            return $tab[1];
154
        } else if (Str::contains($locale, '-'))
155
        {
156
            $tab = explode('-', $locale);
157
            return $tab[1];
158
        }
159
160
        return $locale;
161
    }
162
163 View Code Duplication
    public static function getCountry(string $locale): string
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
    {
165
        if (Str::contains($locale, '_'))
166
        {
167
            $tab = explode('_', $locale);
168
            return $tab[0];
169
        } else if (Str::contains($locale, '-'))
170
        {
171
            $tab = explode('-', $locale);
172
            return $tab[0];
173
        }
174
175
        return config('contentful.default_country');
176
    }
177
178
179
}
180