Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ArgumentsTest.php
Go to the documentation of this file.
1 <?php
8 
10 
16 {
20  protected $_phraseCollector;
21 
28  protected $blackList;
29 
30  protected function setUp()
31  {
32  $this->_phraseCollector = new \Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer\PhraseCollector(
33  new \Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer(),
34  true,
35  \Magento\Framework\Phrase::class
36  );
37 
39  $this->blackList = [
40  // the file below is the only file where strings are translated without corresponding arguments
41  $componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Magento_Translation')
42  . '/Model/Js/DataProvider.php',
43  ];
44  }
45 
46  public function testArguments()
47  {
48  $incorrectNumberOfArgumentsErrors = [];
49  $missedPhraseErrors = [];
50  foreach ($this->_getFiles() as $file) {
51  if (in_array($file, $this->blackList)) {
52  continue;
53  }
54  $this->_phraseCollector->parse($file);
55 
56  foreach ($this->_phraseCollector->getPhrases() as $phrase) {
57  $this->checkEmptyPhrases($phrase, $missedPhraseErrors);
58  $this->checkArgumentMismatch($phrase, $incorrectNumberOfArgumentsErrors);
59  }
60  }
61  $this->assertEmpty(
62  $missedPhraseErrors,
63  sprintf(
64  "\n%d missed phrases were discovered: \n%s",
65  count($missedPhraseErrors),
66  implode("\n\n", $missedPhraseErrors)
67  )
68  );
69  $this->assertEmpty(
70  $incorrectNumberOfArgumentsErrors,
71  sprintf(
72  "\n%d usages of inconsistency the number of arguments and placeholders were discovered: \n%s",
73  count($incorrectNumberOfArgumentsErrors),
74  implode("\n\n", $incorrectNumberOfArgumentsErrors)
75  )
76  );
77  }
78 
85  private function checkEmptyPhrases($phrase, &$missedPhraseErrors)
86  {
87  if (empty(trim($phrase['phrase'], "'\"\t\n\r\0\x0B"))) {
88  $missedPhraseErrors[] = $this->_createMissedPhraseError($phrase);
89  }
90  }
91 
98  private function checkArgumentMismatch($phrase, &$incorrectNumberOfArgumentsErrors)
99  {
100  if (preg_match_all('/%(\w+)/', $phrase['phrase'], $matches) || $phrase['arguments']) {
101  $placeholderCount = count(array_unique($matches[1]));
102 
103  // Check for zend placeholders %placeholder% and sprintf placeholder %s
104  if (preg_match_all('/%((s)|([A-Za-z]+)%)/', $phrase['phrase'], $placeHolders, PREG_OFFSET_CAPTURE)) {
105  foreach ($placeHolders[0] as $ph) {
106  // Check if char after placeholder is not a digit or letter
107  $charAfterPh = $phrase['phrase'][$ph[1] + strlen($ph[0])];
108  if (!preg_match('/[A-Za-z0-9]/', $charAfterPh)) {
109  $placeholderCount--;
110  }
111  }
112  }
113 
114  if ($placeholderCount != $phrase['arguments']) {
115  $incorrectNumberOfArgumentsErrors[] = $this->_createPhraseError($phrase);
116  }
117  }
118  }
119 }
$componentRegistrar
Definition: bootstrap.php:23