I18nUsageValidator.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. require_once __DIR__ . '/I18nValidatorInterface.php';
  3. class I18nUsageValidator implements I18nValidatorInterface {
  4. /** @var array<string> */
  5. private $code;
  6. /** @var array<string,array<string,string>> */
  7. private $reference;
  8. /** @var int */
  9. private $totalEntries = 0;
  10. /** @var int */
  11. private $failedEntries = 0;
  12. /** @var string */
  13. private $result = '';
  14. /**
  15. * @param array<string,array<string,string>> $reference
  16. * @param array<string> $code
  17. */
  18. public function __construct(array $reference, array $code) {
  19. $this->code = $code;
  20. $this->reference = $reference;
  21. }
  22. public function displayReport(): string {
  23. if ($this->failedEntries > $this->totalEntries) {
  24. throw new \RuntimeException('The number of unused strings cannot be higher than the number of strings');
  25. }
  26. if ($this->totalEntries === 0) {
  27. return 'There is no data.' . PHP_EOL;
  28. }
  29. return sprintf('%5.1f%% of translation keys are unused.', $this->failedEntries / $this->totalEntries * 100) . PHP_EOL;
  30. }
  31. public function displayResult(): string {
  32. return $this->result;
  33. }
  34. public function validate(): bool {
  35. foreach ($this->reference as $file => $data) {
  36. foreach ($data as $key => $value) {
  37. $this->totalEntries++;
  38. if (preg_match('/\._$/', $key) && in_array(preg_replace('/\._$/', '', $key), $this->code, true)) {
  39. continue;
  40. }
  41. if (!in_array($key, $this->code, true)) {
  42. $this->result .= sprintf('Unused key %s - %s', $key, $value) . PHP_EOL;
  43. $this->failedEntries++;
  44. continue;
  45. }
  46. }
  47. }
  48. return 0 === $this->failedEntries;
  49. }
  50. }