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

JsonTranslator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 21
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addFile() 0 4 1
A trans() 0 5 2
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
}