Passed
Pull Request — master (#1750)
by Gabriel
66:53 queued 01:47
created

JsonTranslator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\Infrastructure\Translation;
6
7
use FileFetcher\FileFetcher;
8
9
class JsonTranslator implements TranslatorInterface {
10
11
	private FileFetcher $fileFetcher;
12
	private array $messages;
13
14
	public function __construct( FileFetcher $fileFetcher ) {
15
		$this->fileFetcher = $fileFetcher;
16
		$this->messages = [];
17
	}
18
19
	public function addFile( string $fileName ): self {
20
		$contents = $this->fileFetcher->fetchFile( $fileName );
21
		$this->messages = array_merge( $this->messages, json_decode( $contents, true ) );
22
		return $this;
23
	}
24
25
	public function trans( string $messageKey, array $parameters = [] ): string {
26
		if ( !isset( $this->messages[$messageKey] ) ) {
27
			throw new \InvalidArgumentException( "Unknown translation key: $messageKey" );
28
		}
29
		return str_replace( array_keys( $parameters ), array_values( $parameters ), $this->messages[$messageKey] );
30
	}
31
32
}