I18nUsageValidator.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. require_once __DIR__ . '/I18nValidatorInterface.php';
  3. class I18nUsageValidator implements I18nValidatorInterface {
  4. /** @var array<string> */
  5. private array $code;
  6. /** @var array<string,array<string,string>> */
  7. private array $reference;
  8. private int $totalEntries = 0;
  9. private int $failedEntries = 0;
  10. private string $result = '';
  11. /**
  12. * @param array<string,array<string,string>> $reference
  13. * @param array<string> $code
  14. */
  15. public function __construct(array $reference, array $code) {
  16. $this->code = $code;
  17. $this->reference = $reference;
  18. }
  19. public function displayReport(): string {
  20. if ($this->failedEntries > $this->totalEntries) {
  21. throw new \RuntimeException('The number of unused strings cannot be higher than the number of strings');
  22. }
  23. if ($this->totalEntries === 0) {
  24. return 'There is no data.' . PHP_EOL;
  25. }
  26. return sprintf('%5.1f%% of translation keys are unused.', $this->failedEntries / $this->totalEntries * 100) . PHP_EOL;
  27. }
  28. public function displayResult(): string {
  29. return $this->result;
  30. }
  31. public function validate(): bool {
  32. foreach ($this->reference as $file => $data) {
  33. foreach ($data as $key => $value) {
  34. $this->totalEntries++;
  35. if (preg_match('/\._$/', $key) === 1 && in_array(preg_replace('/\._$/', '', $key), $this->code, true)) {
  36. continue;
  37. }
  38. if (!in_array($key, $this->code, true)) {
  39. $this->result .= sprintf('Unused key %s - %s', $key, $value) . PHP_EOL;
  40. $this->failedEntries++;
  41. continue;
  42. }
  43. }
  44. }
  45. return 0 === $this->failedEntries;
  46. }
  47. }