Languages::getLanguagesAttribute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
/** Created by PhpStorm,  User: jonphipps,  Date: 2017-03-01,  Time: 6:16 PM */
4
5
namespace App\Helpers\Macros\Traits;
6
7
use Cache;
8
use Symfony\Component\Intl\Intl;
9
10
trait Languages
11
{
12
    public static function listLanguages($language = '')
13
    {
14
        if ($language) {
15
            return Intl::getLocaleBundle()->getLocaleName($language);
16
        }
17
18
        return Intl::getLocaleBundle()->getLocaleNames();
19
    }
20
21
    public function showLanguage($value = null)
22
    {
23
        $value = $value ?? config('app.locale');
24
25
        return Cache::get('language_' . $value,
26
            function () use ($value) {
27
                return self::listLanguages($value);
28
            });
29
    }
30
31
    public function showLanguagesCommaDelimited(): string
32
    {
33
        $keys = $this->decodeLanguageArray();
34
        if (empty($keys)) {
35
            return '';
36
        }
37
        ksort($keys);
38
        $string = '';
39
        foreach ($keys as $key) {
40
            $string .= Intl::getLocaleBundle()->getLocaleName($key) . ', ';
41
        }
42
43
        return rtrim($string, ', ');
44
    }
45
46
    public function listLanguagesForSelect(): array
47
    {
48
        return Intl::getLocaleBundle()->getLocaleNames();
49
    }
50
51
    private function decodeLanguageArray()
52
    {
53
        $languageProp = $this->attributes['languages'];
54
        if (! empty($languageProp)) {
55
            try {
56
                /* @noinspection UnserializeExploitsInspection */
57
                return unserialize($languageProp);
58
            } catch (\ErrorException $e) {
59
                return json_decode($languageProp);
60
            }
61
        }
62
    }
63
64
    public function getLanguagesAttribute()
65
    {
66
        return $this->decodeLanguageArray();
67
    }
68
69
    public function setLanguagesAttribute($value): void
70
    {
71
        $this->attributes['languages'] = serialize($value);
72
    }
73
}
74