Completed
Push — master ( 4b1496...c64940 )
by Maxime
04:19
created

Locale::getLocale()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 6
rs 9.9666
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
        'fallback_code',
33
        'is_default',
34
        'is_editable',
35
        'is_publishable',
36
    ];
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    protected $casts = [
42
        'is_default' => 'boolean',
43
        'is_editable' => 'boolean',
44
        'is_publishable' => 'boolean',
45
    ];
46
47
    /**
48
     * Return default locale code.
49
     *
50
     * @return string
51
     */
52 View Code Duplication
    public static function default(): string
2 ignored issues
show
Coding Style introduced by
Possible parse error: non-abstract method defined as abstract
Loading history...
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...
53
    {
54
        $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...
55
56
        if ($default === null) {
0 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...
57
            $default = static::query()->select('code')->where('is_default', '=', true)->first();
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...
58
            $default = !empty($default) ? $default->code : 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...
59
            $default = self::getLocale($default);
0 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...
60
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
61
            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...
62
        }
63
64
        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...
65
    }
66
67
68
    public static function getAppOrDefaultLocale(): string
69
    {
70
        return app()->getLocale() ?? self::default();
71
    }
72
73
    public static function getAppOrDefaultCountry($key = 'app.country'): string
74
    {
75
        return config($key, self::defaultCountry());
76
    }
77
78
    /**
79
     * Return default country code.
80
     *
81
     * @return string
82
     */
83 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...
84
    {
85
        $default = Cache::get('country_default');
86
87
        if ($default === null) {
88
            $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...
89
                ->select('code')
90
                ->where('is_default', '=', true)
91
                ->first();
92
            $default = !empty($default) ? $default->code : config('contentful.default_country');
93
            $default = self::getCountry($default);
94
            // Cache is cleaned in Console\Commands\SyncLocales (run at least daily)
95
            Cache::forever('country_default', $default);
96
        }
97
98
        return $default;
99
    }
100
101
    /**
102
     * Return fallback code for given locale code.
103
     *
104
     * @param  string $code
105
     * @return string
106
     */
107
    public static function fallback(string $code): string
108
    {
109
        $fallback = Cache::get('locale_fallback_' . $code);
110
111
        if ($fallback === null) {
112
            $locale = static::query()->select('fallback_code')->where('code', '=', $code)->first();
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...
113
            $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...
114
115
            Cache::put('locale_fallback_' . $code, $fallback, 5);
116
        }
117
118
        return $fallback;
119
    }
120
121
    public static function canBeSave(string $country,string $locale): bool
122
    {
123
        $locales = config('contentful.locales_not_flatten','');
124
        $locales = explode(',',$locales);
125
        return !in_array($country.'_'.$locale,$locales);
126
    }
127
    public static function getLocale(string $locale): string
128
    {
129
        if (Str::contains($locale, '_')) {
130
            $tab = explode('_', $locale);
131
            return $tab[1];
132
        }
133
134
        return $locale;
135
    }
136
137
    public static function getCountry(string $locale): string
138
    {
139
        if (Str::contains($locale, '_')) {
140
            $tab = explode('_', $locale);
141
            return $tab[0];
142
        }
143
144
        return config('contentful.default_country');
145
    }
146
147
    public function getLocaleAttribute(): string
148
    {
149
        return self::getLocale($this->code);
150
    }
151
152
    public function getCountryAttribute(): string
153
    {
154
        return self::getCountry($this->code);
155
    }
156
}
157