Passed
Push — master ( fc7f46...e20581 )
by Jean Paul
01:37
created

i18n::getText()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
nc 8
nop 3
dl 0
loc 21
rs 9.9332
c 1
b 0
f 0
1
<?php
2
3
namespace Coco\SourceWatcher\Utils;
4
5
use Dotenv\Dotenv;
6
use Symfony\Component\Yaml\Yaml;
7
8
class i18n
9
{
10
    /**
11
     * @var i18n|null
12
     */
13
    private static ?i18n $instance = null;
14
15
    /**
16
     * @return i18n
17
     */
18
    public static function getInstance () : i18n
19
    {
20
        if ( is_null( static::$instance ) ) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $instance to at least protected.
Loading history...
21
            static::$instance = new static;
22
        }
23
24
        return static::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::instance could return the type null which is incompatible with the type-hinted return Coco\SourceWatcher\Utils\i18n. Consider adding an additional type-check to rule them out.
Loading history...
25
    }
26
27
    /**
28
     * @return string|null
29
     */
30
    private function getLanguageFromEnvFile () : ?string
31
    {
32
        $dotEnv = Dotenv::createImmutable( __DIR__ . "./../../" );
33
        $dotEnv->load();
34
35
        return array_key_exists( "I18N_LANGUAGE", $_ENV ) ? $_ENV["I18N_LANGUAGE"] : null;
36
    }
37
38
    /**
39
     * @param string $className
40
     * @param string $entry
41
     * @param string|null $language
42
     * @return string
43
     */
44
    public function getText ( string $className, string $entry, string $language = null ) : string
45
    {
46
        if ( empty( $language ) ) {
47
            $language = $this->getLanguageFromEnvFile();
48
        }
49
50
        if ( empty( $language ) ) {
51
            $language = "en_US";
52
        }
53
54
        $data = Yaml::parseFile( __DIR__ . sprintf( "/../../resources/Locales/translations_%s.yml", $language ) );
55
56
        $classPathParts = explode( "\\", $className );
57
58
        $dataCopy = $data;
59
60
        foreach ( $classPathParts as $currentPart ) {
61
            $dataCopy = $dataCopy[$currentPart];
62
        }
63
64
        return $dataCopy[$entry];
65
    }
66
}
67