I18nCompletionValidator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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(): 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. return sprintf('Translation is %5.1f%% complete.', $this->passEntries / $this->totalEntries * 100) . PHP_EOL;
  26. }
  27. #[\Override]
  28. public function displayResult(): string {
  29. return $this->result;
  30. }
  31. #[\Override]
  32. public function validate(): bool {
  33. foreach ($this->reference as $file => $data) {
  34. foreach ($data as $refKey => $refValue) {
  35. $this->totalEntries++;
  36. if (!array_key_exists($file, $this->language) || !array_key_exists($refKey, $this->language[$file])) {
  37. $this->result .= "Missing key $refKey" . PHP_EOL;
  38. continue;
  39. }
  40. $value = $this->language[$file][$refKey];
  41. if ($value->isIgnore()) {
  42. $this->passEntries++;
  43. continue;
  44. }
  45. if ($refValue->equal($value)) {
  46. $this->result .= "Untranslated key $refKey - $refValue" . PHP_EOL;
  47. continue;
  48. }
  49. $this->passEntries++;
  50. }
  51. }
  52. return $this->totalEntries === $this->passEntries;
  53. }
  54. }