I18nCompletionValidator.php 1.8 KB

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