summaryrefslogtreecommitdiff
path: root/cli/i18n/I18nUsageValidator.php
blob: dd514236b0a8e072564ff59b3dd49c87bfb552e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
declare(strict_types=1);

require_once __DIR__ . '/I18nValidatorInterface.php';

class I18nUsageValidator implements I18nValidatorInterface {

	/** @var array<string> */
	private array $code;
	/** @var array<string,array<string,I18nValue>> */
	private array $reference;
	private int $totalEntries = 0;
	private int $failedEntries = 0;
	private string $result = '';

	/**
	 * @param array<string,array<string,I18nValue>> $reference
	 * @param array<string> $code
	 */
	public function __construct(array $reference, array $code) {
		$this->code = $code;
		$this->reference = $reference;
	}

	#[\Override]
	public function displayReport(): string {
		if ($this->failedEntries > $this->totalEntries) {
			throw new \RuntimeException('The number of unused strings cannot be higher than the number of strings');
		}
		if ($this->totalEntries === 0) {
			return 'There is no data.' . PHP_EOL;
		}
		return sprintf('%5.1f%% of translation keys are unused.', $this->failedEntries / $this->totalEntries * 100) . PHP_EOL;
	}

	#[\Override]
	public function displayResult(): string {
		return $this->result;
	}

	#[\Override]
	public function validate(): bool {
		foreach ($this->reference as $file => $data) {
			foreach ($data as $key => $value) {
				$this->totalEntries++;
				if (preg_match('/\._$/', $key) === 1 && in_array(preg_replace('/\._$/', '', $key), $this->code, true)) {
					continue;
				}
				if (!in_array($key, $this->code, true)) {
					$this->result .= sprintf('Unused key %s - %s', $key, $value) . PHP_EOL;
					$this->failedEntries++;
					continue;
				}
			}
		}

		return 0 === $this->failedEntries;
	}

}