Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
TemplatesTest.php
Go to the documentation of this file.
1 <?php
9 
11 
12 class TemplatesTest extends \PHPUnit\Framework\TestCase
13 {
17  protected static $templates = [];
18 
22  protected static $blockVirtualTypes = [];
23 
27  public static function setUpBeforeClass()
28  {
29  $count = 0;
30  self::getBlockVirtualTypesWithDifferentModule();
31  foreach (Files::init()->getLayoutFiles([], false) as $file) {
32  $xml = simplexml_load_file($file);
33  $blocks = $xml->xpath('//block[@template]') ?: [];
34  $fileTemplates = [];
35  foreach ($blocks as $block) {
36  $fileTemplates[] = ['class' => (string)$block['class'], 'file' => (string)$block['template']];
37  }
38  if (!empty($fileTemplates)) {
39  self::$templates[$file] = $fileTemplates;
40  $count += count($fileTemplates);
41  }
42  }
43  }
44 
52  {
53  $errors = [];
54  $warnings = [];
55  foreach (self::$templates as $file => $templates) {
56  foreach ($templates as $templatePair) {
57  if (!preg_match('/[A-Za-z0-9]_[A-Za-z0-9]+\:\:[A-Za-z0-9\\_\-\.]+/', $templatePair['file'])) {
58  if (!isset($errors[$file])) {
59  $errors[$file] = [];
60  }
61  $errors[$file][] = $templatePair['file'];
62  } else {
63  if (isset(self::$blockVirtualTypes[$templatePair['class']])) {
64  $warnings[$file][] = $templatePair;
65  }
66  }
67  }
68  }
69  if (count($errors) > 0) {
70  $message = 'Failed to assert that the template reference follows the canonical format '
71  . 'Vendor' . '_' . 'Module::path/to/template.phtml. Following files haven\'t pass verification:'
72  . PHP_EOL;
73  foreach ($errors as $file => $wrongTemplates) {
74  $message .= $file . ':' . PHP_EOL;
75  $message .= '- ' . implode(PHP_EOL . '- ', $wrongTemplates) . PHP_EOL;
76  }
77  $this->fail($message);
78  }
79  }
80 
86  private static function getBlockVirtualTypesWithDifferentModule()
87  {
88  $virtual = \Magento\Framework\App\Utility\Classes::getVirtualClasses();
89  foreach ($virtual as $className => $resolvedName) {
90  if (strpos($resolvedName, 'Block') !== false) {
91  $matches = [];
92  preg_match('/([A-Za-z0-9]+\\\\[A-Za-z0-9]+).*/', $className, $matches);
93  if (count($matches) > 1) {
94  $oldModule = $matches[1];
95  } else {
96  $oldModule = $className;
97  }
98 
99  $matches = [];
100  preg_match('/([A-Za-z0-9]+\\\\[A-Za-z0-9]+).*/', $resolvedName, $matches);
101  $newModule = $matches[1];
102  if ($oldModule != $newModule) {
103  self::$blockVirtualTypes[$className] = $resolvedName;
104  }
105  }
106  }
107  }
108 }
$count
Definition: recent.phtml:13
$message
$block
Definition: block.php:8
$errors
Definition: overview.phtml:9
if($currentSelectedMethod==$_code) $className
Definition: form.phtml:31