I18nUsageValidator.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare(strict_types=1);
  3. require_once __DIR__ . '/I18nValidatorInterface.php';
  4. class I18nUsageValidator implements I18nValidatorInterface {
  5. private int $totalEntries = 0;
  6. private int $failedEntries = 0;
  7. private string $result = '';
  8. /**
  9. * @param array<string,array<string,I18nValue>> $reference
  10. * @param array<string> $code
  11. */
  12. public function __construct(
  13. private readonly array $reference,
  14. private readonly array $code,
  15. ) {
  16. }
  17. #[\Override]
  18. public function displayReport(): string {
  19. if ($this->failedEntries > $this->totalEntries) {
  20. throw new \RuntimeException('The number of unused 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('%5.1f%% of translation keys are unused.', $this->failedEntries / $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 $key => $value) {
  35. $this->totalEntries++;
  36. if (preg_match('/\._$/', $key) === 1 && in_array(preg_replace('/\._$/', '', $key), $this->code, true)) {
  37. continue;
  38. }
  39. if (!in_array($key, $this->code, true)) {
  40. $this->result .= sprintf('Unused key %s - %s', $key, $value) . PHP_EOL;
  41. $this->failedEntries++;
  42. continue;
  43. }
  44. }
  45. }
  46. return 0 === $this->failedEntries;
  47. }
  48. }