Passed
Push — master ( 292cc5...4a4ead )
by Ivan
04:18
created

Localizer::localeIsAcceptable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace CodeZero\Localizer;
4
5
use Illuminate\Support\Facades\App;
6
7
class Localizer
8
{
9
    /**
10
     * Supported locales.
11
     *
12
     * @var \Illuminate\Support\Collection|array
13
     */
14
    protected $locales;
15
16
    /**
17
     * \CoderZero\Localizer\Detectors\Detector instances.
18
     *
19
     * @var \Illuminate\Support\Collection|array
20
     */
21
    protected $detectors;
22
23
    /**
24
     * \CoderZero\Localizer\Stores\Store instances.
25
     *
26
     * @var \Illuminate\Support\Collection|array
27
     */
28
    protected $stores;
29
30
    /**
31
     * Create a new Localizer instance.
32
     *
33
     * @param \Illuminate\Support\Collection|array $locales
34
     * @param \Illuminate\Support\Collection|array $detectors
35
     * @param \Illuminate\Support\Collection|array $stores
36
     */
37 13
    public function __construct($locales, $detectors, $stores = [])
38
    {
39 13
        $this->locales = $locales;
40 13
        $this->detectors = $detectors;
41 13
        $this->stores = $stores;
42 13
    }
43
44
    /**
45
     * Detect any supported locale and return the first match.
46
     *
47
     * @return string|false
48
     */
49 12
    public function detect()
50
    {
51 12
        foreach ($this->detectors as $detector) {
52 12
            $locales = (array) $this->getInstance($detector)->detect();
53
54 12
            foreach ($locales as $locale) {
55 11
                if ($this->isSupportedLocale($locale)) {
56 12
                    return $locale;
57
                }
58
            }
59
        }
60
61 2
        return false;
62
    }
63
64
    /**
65
     * Store the given locale.
66
     *
67
     * @param string $locale
68
     *
69
     * @return void
70
     */
71 9
    public function store($locale)
72
    {
73 9
        foreach ($this->stores as $store) {
74 9
            $this->getInstance($store)->store($locale);
75
        }
76 9
    }
77
78
    /**
79
     * Check if the given locale is supported.
80
     *
81
     * @param mixed $locale
82
     *
83
     * @return bool
84
     */
85 11
    protected function isSupportedLocale($locale)
86
    {
87 11
        return in_array($locale, $this->locales);
88
    }
89
90
    /**
91
     * Get the class from Laravel's IOC container if it is a string.
92
     *
93
     * @param mixed $class
94
     *
95
     * @return mixed
96
     */
97 13
    protected function getInstance($class)
98
    {
99 13
        if (is_string($class)) {
100 8
            return App::make($class);
101
        }
102
103 5
        return $class;
104
    }
105
}
106