I18nUsageValidator.php 1.3 KB

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