Passed
Push — master ( 7d22f9...1460f7 )
by Jean Paul
01:51
created

Internationalization::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Coco\SourceWatcher\Utils;
4
5
use Dotenv\Dotenv;
6
use Symfony\Component\Yaml\Yaml;
7
8
/**
9
 * Class Internationalization
10
 *
11
 * @package Coco\SourceWatcher\Utils
12
 */
13
class Internationalization
14
{
15
    private static ?Internationalization $instance = null;
16
17
    public static string $I18N_LANGUAGE_INDEX = "I18N_LANGUAGE";
18
19
    public static function getInstance () : Internationalization
20
    {
21
        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...
22
            static::$instance = new static;
23
        }
24
25
        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\Internationalization. Consider adding an additional type-check to rule them out.
Loading history...
26
    }
27
28
    private function getLanguageFromEnvFile () : ?string
29
    {
30
        $language = array_key_exists( Internationalization::$I18N_LANGUAGE_INDEX,
31
            $_ENV ) ? $_ENV[Internationalization::$I18N_LANGUAGE_INDEX] : null;
32
33
        if ( empty( $language ) ) {
34
            $envFileDirectory = __DIR__ . "/../../";
35
            $envFileLocation = $envFileDirectory . ".env";
36
37
            if ( file_exists( $envFileLocation ) ) {
38
                $dotEnv = Dotenv::createImmutable( $envFileDirectory );
39
                $dotEnv->load();
40
41
                $language = array_key_exists( Internationalization::$I18N_LANGUAGE_INDEX,
42
                    $_ENV ) ? $_ENV[Internationalization::$I18N_LANGUAGE_INDEX] : null;
43
            }
44
        }
45
46
        return $language;
47
    }
48
49
    public function getText ( string $className, string $entry, string $language = null ) : string
50
    {
51
        if ( empty( $language ) ) {
52
            $language = $this->getLanguageFromEnvFile();
53
        }
54
55
        if ( empty( $language ) ) {
56
            $language = "en_US";
57
        }
58
59
        $data = Yaml::parseFile( __DIR__ . sprintf( "/../../resources/Locales/translations_%s.yml", $language ) );
60
61
        $classPathParts = explode( "\\", $className );
62
63
        $dataCopy = $data;
64
65
        foreach ( $classPathParts as $currentPart ) {
66
            $dataCopy = $dataCopy[$currentPart];
67
        }
68
69
        return $dataCopy[$entry];
70
    }
71
}
72