1 | <?php |
||
2 | declare(strict_types=1); |
||
3 | |||
4 | /** |
||
5 | * GpsLab component. |
||
6 | * |
||
7 | * @author Peter Gribanov <[email protected]> |
||
8 | * @copyright Copyright (c) 2017, Peter Gribanov |
||
9 | * @license http://opensource.org/licenses/MIT |
||
10 | */ |
||
11 | |||
12 | namespace GpsLab\Bundle\GeoIP2Bundle\Reader; |
||
13 | |||
14 | use GeoIp2\Database\Reader; |
||
15 | |||
16 | class ReaderFactory |
||
17 | { |
||
18 | /** |
||
19 | * @var array<string, ?array{url?: string|false, path?: string|false, locales?: string[], license?: ?string, edition?: string}> |
||
20 | */ |
||
21 | private $databases; |
||
22 | |||
23 | /** |
||
24 | * @var class-string<Reader> |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
25 | */ |
||
26 | private $reader_class; |
||
27 | |||
28 | /** |
||
29 | * @param array<string, ?array{url?: string|false, path?: string|false, locales?: string[], license?: ?string, edition?: string}> $databases |
||
30 | * @param class-string<Reader> $reader_class |
||
0 ignored issues
–
show
|
|||
31 | */ |
||
32 | 15 | public function __construct(array $databases, string $reader_class = Reader::class) |
|
33 | { |
||
34 | 15 | $this->databases = $databases; |
|
35 | 15 | $this->reader_class = $reader_class; |
|
36 | 15 | } |
|
37 | |||
38 | /** |
||
39 | * @param string $database |
||
40 | * @param string[]|null $locales |
||
41 | * |
||
42 | * @return Reader |
||
43 | */ |
||
44 | 15 | public function create(string $database, ?array $locales = null): Reader |
|
45 | { |
||
46 | 15 | if (!array_key_exists($database, $this->databases)) { |
|
47 | 6 | $databases = implode('", "', array_keys($this->databases)); |
|
48 | |||
49 | 6 | throw new \InvalidArgumentException(sprintf('Undefined "%s" database. Available "%s" databases.', $database, $databases)); |
|
50 | } |
||
51 | |||
52 | 9 | if (!is_array($this->databases[$database]) || empty($this->databases[$database]['path'])) { |
|
53 | 6 | throw new \InvalidArgumentException(sprintf('Database "%s" is not configured.', $database)); |
|
54 | } |
||
55 | |||
56 | 3 | if ($locales === null) { |
|
57 | 1 | $locales = $this->databases[$database]['locales'] ?? ['en']; |
|
58 | } |
||
59 | |||
60 | 3 | return new $this->reader_class($this->databases[$database]['path'], $locales); |
|
61 | } |
||
62 | } |
||
63 |