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. /** @var array<string> */
  6. private array $code;
  7. /** @var array<string,array<string,I18nValue>> */
  8. private array $reference;
  9. private int $totalEntries = 0;
  10. private int $failedEntries = 0;
  11. private string $result = '';
  12. /**
  13. * @param array<string,array<string,I18nValue>> $reference
  14. * @param array<string> $code
  15. */
  16. public function __construct(array $reference, array $code) {
  17. $this->code = $code;
  18. $this->reference = $reference;
  19. }
  20. public function displayReport(): string {
  21. if ($this->failedEntries > $this->totalEntries) {
  22. throw new \RuntimeException('The number of unused strings cannot be higher than the number of strings');
  23. }
  24. if ($this->totalEntries === 0) {
  25. return 'There is no data.' . PHP_EOL;
  26. }
  27. return sprintf('%5.1f%% of translation keys are unused.', $this->failedEntries / $this->totalEntries * 100) . PHP_EOL;
  28. }
  29. public function displayResult(): string {
  30. return $this->result;
  31. }
  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. }