I18nCompletionValidator.php 1.8 KB

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