I18nUsageValidator.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. * @param array<string> $codePrefixes
  12. */
  13. public function __construct(
  14. private readonly array $reference,
  15. private readonly array $code,
  16. private readonly array $codePrefixes = [],
  17. ) {
  18. }
  19. private function isUsed(string $key): bool {
  20. if (preg_match('/\._$/', $key) === 1 && in_array(preg_replace('/\._$/', '', $key), $this->code, true)) {
  21. return true;
  22. }
  23. if (in_array($key, $this->code, true)) {
  24. return true;
  25. }
  26. foreach ($this->codePrefixes as $prefix) {
  27. if (str_starts_with($key, $prefix)) {
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. #[\Override]
  34. public function displayReport(bool $percentage_only = false): string {
  35. if ($this->failedEntries > $this->totalEntries) {
  36. throw new \RuntimeException('The number of unused strings cannot be higher than the number of strings');
  37. }
  38. if ($this->totalEntries === 0) {
  39. return 'There is no data.' . PHP_EOL;
  40. }
  41. if ($percentage_only) {
  42. return '100%';
  43. }
  44. return sprintf('%5.1f%% of translation keys are unused.', $this->failedEntries / $this->totalEntries * 100) . PHP_EOL;
  45. }
  46. #[\Override]
  47. public function displayResult(): string {
  48. return $this->result;
  49. }
  50. #[\Override]
  51. public function validate(): bool {
  52. foreach ($this->reference as $file => $data) {
  53. foreach ($data as $key => $value) {
  54. $this->totalEntries++;
  55. if (!$this->isUsed($key)) {
  56. $this->result .= sprintf('Unused key %s - %s', $key, $value) . PHP_EOL;
  57. $this->failedEntries++;
  58. continue;
  59. }
  60. }
  61. }
  62. return 0 === $this->failedEntries;
  63. }
  64. }