I18nCompletionValidator.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. require_once __DIR__ . '/I18nValidatorInterface.php';
  3. class I18nCompletionValidator implements I18nValidatorInterface {
  4. /** @var array<string,array<string,I18nValue>> */
  5. private $reference;
  6. /** @var array<string,array<string,I18nValue>> */
  7. private $language;
  8. /** @var int */
  9. private $totalEntries = 0;
  10. /** @var int */
  11. private $passEntries = 0;
  12. /** @var string */
  13. private $result = '';
  14. /**
  15. * @param array<string,array<string,I18nValue>> $reference
  16. * @param array<string,array<string,I18nValue>> $language
  17. */
  18. public function __construct(array $reference, array $language) {
  19. $this->reference = $reference;
  20. $this->language = $language;
  21. }
  22. public function displayReport(): string {
  23. if ($this->passEntries > $this->totalEntries) {
  24. throw new \RuntimeException('The number of translated strings cannot be higher than the number of strings');
  25. }
  26. if ($this->totalEntries === 0) {
  27. return 'There is no data.' . PHP_EOL;
  28. }
  29. return sprintf('Translation is %5.1f%% complete.', $this->passEntries / $this->totalEntries * 100) . PHP_EOL;
  30. }
  31. public function displayResult(): string {
  32. return $this->result;
  33. }
  34. public function validate(): bool {
  35. foreach ($this->reference as $file => $data) {
  36. foreach ($data as $refKey => $refValue) {
  37. $this->totalEntries++;
  38. if (!array_key_exists($file, $this->language) || !array_key_exists($refKey, $this->language[$file])) {
  39. $this->result .= "Missing key $refKey" . PHP_EOL;
  40. continue;
  41. }
  42. $value = $this->language[$file][$refKey];
  43. if ($value->isIgnore()) {
  44. $this->passEntries++;
  45. continue;
  46. }
  47. if ($refValue->equal($value)) {
  48. $this->result .= "Untranslated key $refKey - $refValue" . PHP_EOL;
  49. continue;
  50. }
  51. $this->passEntries++;
  52. }
  53. }
  54. return $this->totalEntries === $this->passEntries;
  55. }
  56. }