I18nCompletionValidator.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. require_once __DIR__ . '/I18nValidatorInterface.php';
  3. class I18nCompletionValidator implements I18nValidatorInterface {
  4. /** @var array<string,array<string,I18nValue>> */
  5. private array $reference;
  6. /** @var array<string,array<string,I18nValue>> */
  7. private array $language;
  8. private int $totalEntries = 0;
  9. private int $passEntries = 0;
  10. private string $result = '';
  11. /**
  12. * @param array<string,array<string,I18nValue>> $reference
  13. * @param array<string,array<string,I18nValue>> $language
  14. */
  15. public function __construct(array $reference, array $language) {
  16. $this->reference = $reference;
  17. $this->language = $language;
  18. }
  19. public function displayReport(): string {
  20. if ($this->passEntries > $this->totalEntries) {
  21. throw new \RuntimeException('The number of translated 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('Translation is %5.1f%% complete.', $this->passEntries / $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 $refKey => $refValue) {
  34. $this->totalEntries++;
  35. if (!array_key_exists($file, $this->language) || !array_key_exists($refKey, $this->language[$file])) {
  36. $this->result .= "Missing key $refKey" . PHP_EOL;
  37. continue;
  38. }
  39. $value = $this->language[$file][$refKey];
  40. if ($value->isIgnore()) {
  41. $this->passEntries++;
  42. continue;
  43. }
  44. if ($refValue->equal($value)) {
  45. $this->result .= "Untranslated key $refKey - $refValue" . PHP_EOL;
  46. continue;
  47. }
  48. $this->passEntries++;
  49. }
  50. }
  51. return $this->totalEntries === $this->passEntries;
  52. }
  53. }