ReaderFactory::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 1
b 0
f 0
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
The doc comment class-string<Reader> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<Reader>.
Loading history...
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
Documentation Bug introduced by
The doc comment class-string<Reader> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<Reader>.
Loading history...
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