DependencyTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. <?php
  2. /**
  3. * Scan source code for incorrect or undeclared modules dependencies
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. *
  8. */
  9. namespace Magento\Test\Integrity;
  10. use Magento\Framework\App\Utility\Files;
  11. use Magento\Framework\Component\ComponentRegistrar;
  12. use Magento\TestFramework\Dependency\DbRule;
  13. use Magento\TestFramework\Dependency\DeclarativeSchemaRule;
  14. use Magento\TestFramework\Dependency\DiRule;
  15. use Magento\TestFramework\Dependency\LayoutRule;
  16. use Magento\TestFramework\Dependency\PhpRule;
  17. use Magento\TestFramework\Dependency\ReportsConfigRule;
  18. use Magento\TestFramework\Dependency\AnalyticsConfigRule;
  19. use Magento\TestFramework\Dependency\VirtualType\VirtualTypeMapper;
  20. /**
  21. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  22. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  23. */
  24. class DependencyTest extends \PHPUnit\Framework\TestCase
  25. {
  26. /**
  27. * Types of dependencies between modules
  28. */
  29. const TYPE_SOFT = 'soft';
  30. const TYPE_HARD = 'hard';
  31. /**
  32. * Types of dependencies map arrays
  33. */
  34. const MAP_TYPE_DECLARED = 'declared';
  35. const MAP_TYPE_FOUND = 'found';
  36. const MAP_TYPE_REDUNDANT = 'redundant';
  37. /**
  38. * Count of directories in path
  39. */
  40. const DIR_PATH_COUNT = 4;
  41. /**
  42. * List of config.xml files by modules
  43. *
  44. * Format: array(
  45. * '{Module_Name}' => '{Filename}'
  46. * )
  47. *
  48. * @var array
  49. */
  50. protected static $_listConfigXml = [];
  51. /**
  52. * List of db_schema.xml files by modules
  53. *
  54. * Format: array(
  55. * '{Module_Name}' => '{Filename}'
  56. * )
  57. *
  58. * @var array
  59. */
  60. protected static $_listDbSchemaXml = [];
  61. /**
  62. * List of routes.xml files by modules
  63. *
  64. * Format: array(
  65. * '{Module_Name}' => '{Filename}'
  66. * )
  67. *
  68. * @var array
  69. */
  70. protected static $_listRoutesXml = [];
  71. /**
  72. * List of analytics.xml
  73. *
  74. * Format: array(
  75. * '{Module_Name}' => '{Filename}'
  76. * )
  77. *
  78. * @var array
  79. */
  80. protected static $_listAnalyticsXml = [];
  81. /**
  82. * List of routers
  83. *
  84. * Format: array(
  85. * '{Router}' => '{Module_Name}'
  86. * )
  87. *
  88. * @var array
  89. */
  90. protected static $_mapRouters = [];
  91. /**
  92. * List of layout blocks
  93. *
  94. * Format: array(
  95. * '{Area}' => array(
  96. * '{Block_Name}' => array('{Module_Name}' => '{Module_Name}')
  97. * ))
  98. *
  99. * @var array
  100. */
  101. protected static $_mapLayoutBlocks = [];
  102. /**
  103. * List of layout handles
  104. *
  105. * Format: array(
  106. * '{Area}' => array(
  107. * '{Handle_Name}' => array('{Module_Name}' => '{Module_Name}')
  108. * ))
  109. *
  110. * @var array
  111. */
  112. protected static $_mapLayoutHandles = [];
  113. /**
  114. * List of dependencies
  115. *
  116. * Format: array(
  117. * '{Module_Name}' => array(
  118. * '{Type}' => array(
  119. * 'declared' = array('{Dependency}', ...)
  120. * 'found' = array('{Dependency}', ...)
  121. * 'redundant' = array('{Dependency}', ...)
  122. * )))
  123. * @var array
  124. */
  125. protected static $mapDependencies = [];
  126. /**
  127. * Regex pattern for validation file path of theme
  128. *
  129. * @var string
  130. */
  131. protected static $_defaultThemes = '';
  132. /**
  133. * Namespaces to analyze
  134. *
  135. * Format: {Namespace}|{Namespace}|...
  136. *
  137. * @var string
  138. */
  139. protected static $_namespaces;
  140. /**
  141. * Rule instances
  142. *
  143. * @var array
  144. */
  145. protected static $_rulesInstances = [];
  146. /**
  147. * White list for libraries
  148. *
  149. * @var array
  150. */
  151. private static $whiteList = [];
  152. /**
  153. * Sets up data
  154. */
  155. public static function setUpBeforeClass()
  156. {
  157. $root = BP;
  158. $rootJson = json_decode(file_get_contents($root . '/composer.json'), true);
  159. if (preg_match('/magento\/project-*/', $rootJson['name']) == 1) {
  160. // The Dependency test is skipped for vendor/magento build
  161. self::markTestSkipped(
  162. 'MAGETWO-43654: The build is running from vendor/magento. DependencyTest is skipped.'
  163. );
  164. }
  165. self::$_namespaces = implode('|', Files::init()->getNamespaces());
  166. self::_prepareListConfigXml();
  167. self::_prepareListDbSchemaXml();
  168. self::_prepareListRoutesXml();
  169. self::_prepareListAnalyticsXml();
  170. self::_prepareMapRouters();
  171. self::_prepareMapLayoutBlocks();
  172. self::_prepareMapLayoutHandles();
  173. self::getLibraryWhiteLists();
  174. self::_initDependencies();
  175. self::_initThemes();
  176. self::_initRules();
  177. }
  178. /**
  179. * Initialize library white list
  180. */
  181. private static function getLibraryWhiteLists()
  182. {
  183. $componentRegistrar = new ComponentRegistrar();
  184. foreach ($componentRegistrar->getPaths(ComponentRegistrar::LIBRARY) as $library) {
  185. $library = str_replace('\\', '/', $library);
  186. if (strpos($library, 'Framework/') !== false) {
  187. $partOfLibraryPath = explode('/', $library);
  188. self::$whiteList[] = implode('\\', array_slice($partOfLibraryPath, -3));
  189. }
  190. }
  191. }
  192. /**
  193. * Initialize default themes
  194. */
  195. protected static function _initThemes()
  196. {
  197. $defaultThemes = [];
  198. foreach (self::$_listConfigXml as $file) {
  199. $config = simplexml_load_file($file);
  200. $nodes = @($config->xpath("/config/*/design/theme/full_name") ?: []);
  201. foreach ($nodes as $node) {
  202. $defaultThemes[] = (string)$node;
  203. }
  204. }
  205. self::$_defaultThemes = sprintf('#app/design.*/(%s)/.*#', implode('|', array_unique($defaultThemes)));
  206. }
  207. /**
  208. * Create rules objects
  209. */
  210. protected static function _initRules()
  211. {
  212. $replaceFilePattern = str_replace('\\', '/', realpath(__DIR__)) . '/_files/dependency_test/*.php';
  213. $dbRuleTables = [];
  214. foreach (glob($replaceFilePattern) as $fileName) {
  215. $dbRuleTables = array_merge($dbRuleTables, @include $fileName);
  216. }
  217. self::$_rulesInstances = [
  218. new DeclarativeSchemaRule($dbRuleTables),
  219. new PhpRule(self::$_mapRouters, self::$_mapLayoutBlocks),
  220. new DbRule($dbRuleTables),
  221. new LayoutRule(
  222. self::$_mapRouters,
  223. self::$_mapLayoutBlocks,
  224. self::$_mapLayoutHandles
  225. ),
  226. new DiRule(new VirtualTypeMapper()),
  227. new ReportsConfigRule($dbRuleTables),
  228. new AnalyticsConfigRule(),
  229. ];
  230. }
  231. /**
  232. * Return cleaned file contents
  233. *
  234. * @param string $fileType
  235. * @param string $file
  236. * @return string
  237. */
  238. protected function _getCleanedFileContents($fileType, $file)
  239. {
  240. $contents = (string)file_get_contents($file);
  241. switch ($fileType) {
  242. case 'php':
  243. //Removing php comments
  244. $contents = preg_replace('~/\*.*?\*/~s', '', $contents);
  245. $contents = preg_replace('~^\s*//.*$~m', '', $contents);
  246. break;
  247. case 'layout':
  248. case 'config':
  249. case 'db_schema':
  250. //Removing xml comments
  251. $contents = preg_replace('~\<!\-\-/.*?\-\-\>~s', '', $contents);
  252. break;
  253. case 'template':
  254. //Removing html
  255. $contentsWithoutHtml = '';
  256. preg_replace_callback(
  257. '~(<\?php\s+.*\?>)~sU',
  258. function ($matches) use ($contents, &$contentsWithoutHtml) {
  259. $contentsWithoutHtml .= $matches[1];
  260. return $contents;
  261. },
  262. $contents
  263. );
  264. $contents = $contentsWithoutHtml;
  265. //Removing php comments
  266. $contents = preg_replace('~/\*.*?\*/~s', '', $contents);
  267. $contents = preg_replace('~^\s*//.*$~s', '', $contents);
  268. break;
  269. }
  270. return $contents;
  271. }
  272. public function testUndeclared()
  273. {
  274. $invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
  275. $invoker(
  276. /**
  277. * Check undeclared modules dependencies for specified file
  278. *
  279. * @param string $fileType
  280. * @param string $file
  281. */
  282. function ($fileType, $file) {
  283. // Validates file when it is belonged to default themes
  284. $componentRegistrar = new ComponentRegistrar();
  285. foreach ($componentRegistrar->getPaths(ComponentRegistrar::THEME) as $themeDir) {
  286. if (strpos($file, $themeDir . '/') !== false) {
  287. return;
  288. }
  289. }
  290. $foundModuleName = '';
  291. foreach ($componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $moduleName => $moduleDir) {
  292. if (strpos($file, $moduleDir . '/') !== false) {
  293. $foundModuleName = str_replace('_', '\\', $moduleName);
  294. break;
  295. }
  296. }
  297. if (empty($foundModuleName)) {
  298. return;
  299. }
  300. $module = $foundModuleName;
  301. $contents = $this->_getCleanedFileContents($fileType, $file);
  302. $dependencies = $this->getDependenciesFromFiles($module, $fileType, $file, $contents);
  303. // Collect dependencies
  304. $undeclaredDependency = $this->_collectDependencies($module, $dependencies);
  305. // Prepare output message
  306. $result = [];
  307. foreach ($undeclaredDependency as $type => $modules) {
  308. $modules = array_unique($modules);
  309. if (!count($modules)) {
  310. continue;
  311. }
  312. $result[] = sprintf("%s [%s]", $type, implode(', ', $modules));
  313. }
  314. if (count($result)) {
  315. $this->fail('Module ' . $module . ' has undeclared dependencies: ' . implode(', ', $result));
  316. }
  317. },
  318. $this->getAllFiles()
  319. );
  320. }
  321. /**
  322. * Retrieve dependencies from files
  323. *
  324. * @param string $module
  325. * @param string $fileType
  326. * @param string $file
  327. * @param string $contents
  328. * @return string[]
  329. */
  330. protected function getDependenciesFromFiles($module, $fileType, $file, $contents)
  331. {
  332. // Apply rules
  333. $dependencies = [];
  334. foreach (self::$_rulesInstances as $rule) {
  335. /** @var \Magento\TestFramework\Dependency\RuleInterface $rule */
  336. $newDependencies = $rule->getDependencyInfo($module, $fileType, $file, $contents);
  337. $dependencies = array_merge($dependencies, $newDependencies);
  338. }
  339. foreach ($dependencies as $key => $dependency) {
  340. foreach (self::$whiteList as $namespace) {
  341. if (strpos($dependency['source'], $namespace) !== false) {
  342. $dependency['module'] = $namespace;
  343. $dependencies[$key] = $dependency;
  344. }
  345. }
  346. }
  347. return $dependencies;
  348. }
  349. /**
  350. * Collect dependencies
  351. *
  352. * @param string $currentModuleName
  353. * @param array $dependencies
  354. * @return array
  355. */
  356. protected function _collectDependencies($currentModuleName, $dependencies = [])
  357. {
  358. if (!count($dependencies)) {
  359. return [];
  360. }
  361. $undeclared = [];
  362. foreach ($dependencies as $dependency) {
  363. $this->collectDependency($dependency, $currentModuleName, $undeclared);
  364. }
  365. return $undeclared;
  366. }
  367. /**
  368. * Collect a dependency
  369. *
  370. * @param string $currentModule
  371. * @param array $dependency
  372. * @param array $undeclared
  373. */
  374. private function collectDependency($dependency, $currentModule, &$undeclared)
  375. {
  376. $module = $dependency['module'];
  377. $nsModule = str_replace('_', '\\', $module);
  378. $type = isset($dependency['type']) ? $dependency['type'] : self::TYPE_HARD;
  379. $soft = $this->_getDependencies($currentModule, self::TYPE_SOFT, self::MAP_TYPE_DECLARED);
  380. $hard = $this->_getDependencies($currentModule, self::TYPE_HARD, self::MAP_TYPE_DECLARED);
  381. $declared = $type == self::TYPE_SOFT ? array_merge($soft, $hard) : $hard;
  382. if (!in_array($module, $declared) && !in_array($nsModule, $declared) && !$this->_isFake($nsModule)) {
  383. $undeclared[$type][] = $module;
  384. } elseif ((in_array($module, $declared) || in_array($nsModule, $declared)) && $this->_isFake($nsModule)) {
  385. $this->_setDependencies($currentModule, $type, self::MAP_TYPE_REDUNDANT, $module);
  386. }
  387. $this->addDependency($currentModule, $type, self::MAP_TYPE_FOUND, $nsModule);
  388. }
  389. /**
  390. * Collect redundant dependencies
  391. * @SuppressWarnings(PHPMD.NPathComplexity)
  392. * @test
  393. * @depends testUndeclared
  394. */
  395. public function collectRedundant()
  396. {
  397. foreach (array_keys(self::$mapDependencies) as $module) {
  398. $declared = $this->_getDependencies($module, self::TYPE_HARD, self::MAP_TYPE_DECLARED);
  399. $found = array_merge(
  400. $this->_getDependencies($module, self::TYPE_HARD, self::MAP_TYPE_FOUND),
  401. $this->_getDependencies($module, self::TYPE_SOFT, self::MAP_TYPE_FOUND)
  402. );
  403. $found['Magento\Framework'] = 'Magento\Framework';
  404. $this->_setDependencies($module, self::TYPE_HARD, self::MAP_TYPE_REDUNDANT, array_diff($declared, $found));
  405. }
  406. }
  407. /**
  408. * Check redundant dependencies
  409. *
  410. * @depends collectRedundant
  411. */
  412. public function testRedundant()
  413. {
  414. $output = [];
  415. foreach (array_keys(self::$mapDependencies) as $module) {
  416. $result = [];
  417. $redundant = $this->_getDependencies($module, self::TYPE_HARD, self::MAP_TYPE_REDUNDANT);
  418. if (count($redundant)) {
  419. $result[] = sprintf(
  420. "\r\nModule %s: %s [%s]",
  421. $module,
  422. self::TYPE_HARD,
  423. implode(', ', array_values($redundant))
  424. );
  425. }
  426. if (count($result)) {
  427. $output[] = implode(', ', $result);
  428. }
  429. }
  430. if (count($output)) {
  431. $this->fail("Redundant dependencies found!\r\n" . implode(' ', $output));
  432. }
  433. }
  434. /**
  435. * Convert file list to data provider structure
  436. *
  437. * @param string $fileType
  438. * @param array $files
  439. * @param bool|null $skip
  440. * @return array
  441. */
  442. protected function _prepareFiles($fileType, $files, $skip = null)
  443. {
  444. $result = [];
  445. foreach ($files as $relativePath => $file) {
  446. $absolutePath = $file[0];
  447. if (!$skip && substr_count($relativePath, '/') < self::DIR_PATH_COUNT) {
  448. continue;
  449. }
  450. $result[$relativePath] = [$fileType, $absolutePath];
  451. }
  452. return $result;
  453. }
  454. /**
  455. * Return all files
  456. *
  457. * @return array
  458. */
  459. public function getAllFiles()
  460. {
  461. $files = [];
  462. // Get all php files
  463. $files = array_merge(
  464. $files,
  465. $this->_prepareFiles(
  466. 'php',
  467. Files::init()->getPhpFiles(Files::INCLUDE_APP_CODE | Files::AS_DATA_SET | Files::INCLUDE_NON_CLASSES),
  468. true
  469. )
  470. );
  471. // Get all configuration files
  472. $files = array_merge(
  473. $files,
  474. $this->_prepareFiles('config', Files::init()->getConfigFiles())
  475. );
  476. // Get all configuration files
  477. $files = array_merge(
  478. $files,
  479. $this->_prepareFiles('db_schema', Files::init()->getDbSchemaFiles())
  480. );
  481. //Get all layout updates files
  482. $files = array_merge(
  483. $files,
  484. $this->_prepareFiles('layout', Files::init()->getLayoutFiles())
  485. );
  486. // Get all template files
  487. $files = array_merge(
  488. $files,
  489. $this->_prepareFiles('template', Files::init()->getPhtmlFiles())
  490. );
  491. return $files;
  492. }
  493. /**
  494. * Prepare list of config.xml files (by modules).
  495. */
  496. protected static function _prepareListConfigXml()
  497. {
  498. $files = Files::init()->getConfigFiles('config.xml', [], false);
  499. foreach ($files as $file) {
  500. if (preg_match('/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)) {
  501. $module = $matches['namespace'] . '\\' . $matches['module'];
  502. self::$_listConfigXml[$module] = $file;
  503. }
  504. }
  505. }
  506. /**
  507. * Prepare list of db_schema.xml files (by modules)
  508. */
  509. protected static function _prepareListDbSchemaXml()
  510. {
  511. $files = Files::init()->getDbSchemaFiles('db_schema.xml', [], false);
  512. foreach ($files as $file) {
  513. if (preg_match('/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)) {
  514. $module = $matches['namespace'] . '\\' . $matches['module'];
  515. self::$_listDbSchemaXml[$module] = $file;
  516. }
  517. }
  518. }
  519. /**
  520. * Prepare list of routes.xml files (by modules)
  521. */
  522. protected static function _prepareListRoutesXml()
  523. {
  524. $files = Files::init()->getConfigFiles('*/routes.xml', [], false);
  525. foreach ($files as $file) {
  526. if (preg_match('/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)) {
  527. $module = $matches['namespace'] . '\\' . $matches['module'];
  528. self::$_listRoutesXml[$module][] = $file;
  529. }
  530. }
  531. }
  532. /**
  533. * Prepare list of analytics.xml files
  534. */
  535. protected static function _prepareListAnalyticsXml()
  536. {
  537. $files = Files::init()->getDbSchemaFiles('analytics.xml', [], false);
  538. foreach ($files as $file) {
  539. if (preg_match('/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)) {
  540. $module = $matches['namespace'] . '\\' . $matches['module'];
  541. self::$_listAnalyticsXml[$module] = $file;
  542. }
  543. }
  544. }
  545. /**
  546. * Prepare map of routers
  547. */
  548. protected static function _prepareMapRouters()
  549. {
  550. $pattern = '/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)\/Controller\/' .
  551. '(?<path>[\/\w]*).php/';
  552. $files = Files::init()->getPhpFiles(Files::INCLUDE_APP_CODE | Files::INCLUDE_NON_CLASSES);
  553. foreach ($files as $file) {
  554. if (preg_match($pattern, $file, $matches)) {
  555. $module = $matches['namespace'] . '\\' . $matches['module'];
  556. if (!empty(self::$_listRoutesXml[$module])) {
  557. foreach (self::$_listRoutesXml[$module] as $configFile) {
  558. self::updateRoutersMap($module, $configFile);
  559. }
  560. }
  561. }
  562. }
  563. }
  564. /**
  565. * Update routers map for the module basing on the routing config file
  566. *
  567. * @param string $module
  568. * @param string $configFile
  569. *
  570. * @return void
  571. */
  572. private static function updateRoutersMap($module, $configFile)
  573. {
  574. // Read module's routes.xml file
  575. $config = simplexml_load_file($configFile);
  576. $nodes = $config->xpath("/config/router/*");
  577. foreach ($nodes as $node) {
  578. $id = (string)$node['id'];
  579. if ($id != 'adminhtml' && '' == (string)$node['frontName']) {
  580. // Exclude overridden routers
  581. continue;
  582. }
  583. if (!isset(self::$_mapRouters[$id])) {
  584. self::$_mapRouters[$id] = [];
  585. }
  586. if (!in_array($module, self::$_mapRouters[$id])) {
  587. self::$_mapRouters[$id][] = $module;
  588. }
  589. }
  590. }
  591. /**
  592. * Prepare map of layout blocks
  593. */
  594. protected static function _prepareMapLayoutBlocks()
  595. {
  596. $files = Files::init()->getLayoutFiles([], false);
  597. foreach ($files as $file) {
  598. $area = 'default';
  599. if (preg_match('/[\/](?<area>adminhtml|frontend)[\/]/', $file, $matches)) {
  600. $area = $matches['area'];
  601. self::$_mapLayoutBlocks[$area] = @(self::$_mapLayoutBlocks[$area] ?: []);
  602. }
  603. if (preg_match('/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)) {
  604. $module = $matches['namespace'] . '\\' . $matches['module'];
  605. $xml = simplexml_load_file($file);
  606. foreach ((array)$xml->xpath('//container | //block') as $element) {
  607. /** @var \SimpleXMLElement $element */
  608. $attributes = $element->attributes();
  609. $block = (string)$attributes->name;
  610. if (!empty($block)) {
  611. self::$_mapLayoutBlocks[$area][$block] = @(self::$_mapLayoutBlocks[$area][$block] ?: []);
  612. self::$_mapLayoutBlocks[$area][$block][$module] = $module;
  613. }
  614. }
  615. }
  616. }
  617. }
  618. /**
  619. * Prepare map of layout handles
  620. */
  621. protected static function _prepareMapLayoutHandles()
  622. {
  623. $files = Files::init()->getLayoutFiles([], false);
  624. foreach ($files as $file) {
  625. $area = 'default';
  626. if (preg_match('/\/(?<area>adminhtml|frontend)\//', $file, $matches)) {
  627. $area = $matches['area'];
  628. self::$_mapLayoutHandles[$area] = @(self::$_mapLayoutHandles[$area] ?: []);
  629. }
  630. if (preg_match('/app\/code\/(?<namespace>[A-Z][a-z]+)[_\/\\\\](?<module>[A-Z][a-zA-Z]+)/', $file, $matches)
  631. ) {
  632. $module = $matches['namespace'] . '\\' . $matches['module'];
  633. $xml = simplexml_load_file($file);
  634. foreach ((array)$xml->xpath('/layout/child::*') as $element) {
  635. /** @var \SimpleXMLElement $element */
  636. $handle = $element->getName();
  637. self::$_mapLayoutHandles[$area][$handle] = @(self::$_mapLayoutHandles[$area][$handle] ?: []);
  638. self::$_mapLayoutHandles[$area][$handle][$module] = $module;
  639. }
  640. }
  641. }
  642. }
  643. /**
  644. * Retrieve dependency types array
  645. *
  646. * @return array
  647. */
  648. protected static function _getTypes()
  649. {
  650. return [self::TYPE_HARD, self::TYPE_SOFT];
  651. }
  652. /**
  653. * Converts a composer json component name into the Magento Module form
  654. *
  655. * @param string $jsonName The name of a composer json component or dependency e.g. 'magento/module-theme'
  656. * @param array $packageModuleMap Mapping package name with module namespace.
  657. * @return string The corresponding Magento Module e.g. 'Magento\Theme'
  658. */
  659. protected static function convertModuleName(string $jsonName, array $packageModuleMap): string
  660. {
  661. if (isset($packageModuleMap[$jsonName])) {
  662. return $packageModuleMap[$jsonName];
  663. }
  664. if (strpos($jsonName, 'magento/magento') !== false || strpos($jsonName, 'magento/framework') !== false) {
  665. $moduleName = str_replace('/', "\t", $jsonName);
  666. $moduleName = str_replace('framework-', "Framework\t", $moduleName);
  667. $moduleName = str_replace('-', ' ', $moduleName);
  668. $moduleName = ucwords($moduleName);
  669. $moduleName = str_replace("\t", '\\', $moduleName);
  670. $moduleName = str_replace(' ', '', $moduleName);
  671. return $moduleName;
  672. }
  673. return $jsonName;
  674. }
  675. /**
  676. * Initialise map of dependencies.
  677. *
  678. * @return void
  679. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  680. * @SuppressWarnings(PHPMD.NPathComplexity)
  681. * @throws \Exception
  682. */
  683. protected static function _initDependencies()
  684. {
  685. $packageModuleMap = self::getPackageModuleMapping();
  686. $jsonFiles = Files::init()->getComposerFiles(ComponentRegistrar::MODULE, false);
  687. foreach ($jsonFiles as $file) {
  688. $contents = file_get_contents($file);
  689. $decodedJson = json_decode($contents);
  690. if (null == $decodedJson) {
  691. throw new \Exception("Invalid Json: $file");
  692. }
  693. $json = new \Magento\Framework\Config\Composer\Package(json_decode($contents));
  694. $moduleName = self::convertModuleName($json->get('name'), $packageModuleMap);
  695. if (!isset(self::$mapDependencies[$moduleName])) {
  696. self::$mapDependencies[$moduleName] = [];
  697. }
  698. foreach (self::_getTypes() as $type) {
  699. if (!isset(self::$mapDependencies[$moduleName][$type])) {
  700. self::$mapDependencies[$moduleName][$type] = [
  701. self::MAP_TYPE_DECLARED => [],
  702. self::MAP_TYPE_FOUND => [],
  703. self::MAP_TYPE_REDUNDANT => [],
  704. ];
  705. }
  706. }
  707. $require = array_keys((array)$json->get('require'));
  708. self::addDependencies($moduleName, $require, self::TYPE_HARD, $packageModuleMap);
  709. $suggest = array_keys((array)$json->get('suggest'));
  710. self::addDependencies($moduleName, $suggest, self::TYPE_SOFT, $packageModuleMap);
  711. }
  712. }
  713. /**
  714. * Add dependencies to dependency list.
  715. *
  716. * @param string $moduleName
  717. * @param array $packageNames
  718. * @param string $type
  719. * @param array $packageModuleMap
  720. *
  721. * @return void
  722. */
  723. private static function addDependencies(
  724. string $moduleName,
  725. array $packageNames,
  726. string $type,
  727. array $packageModuleMap
  728. ): void {
  729. $packageNames = array_filter($packageNames, function ($packageName) use ($packageModuleMap) {
  730. return isset($packageModuleMap[$packageName]) ||
  731. 0 === strpos($packageName, 'magento/') && 'magento/magento-composer-installer' != $packageName;
  732. });
  733. foreach ($packageNames as $packageName) {
  734. self::addDependency(
  735. $moduleName,
  736. $type,
  737. self::MAP_TYPE_DECLARED,
  738. self::convertModuleName($packageName, $packageModuleMap)
  739. );
  740. }
  741. }
  742. /**
  743. * Add dependency map items.
  744. *
  745. * @param string $module
  746. * @param string $type
  747. * @param string $mapType
  748. * @param string $dependency
  749. *
  750. * @return void
  751. */
  752. private static function addDependency(string $module, string $type, string $mapType, string $dependency): void
  753. {
  754. if (isset(self::$mapDependencies[$module][$type][$mapType])) {
  755. self::$mapDependencies[$module][$type][$mapType][$dependency] = $dependency;
  756. }
  757. }
  758. /**
  759. * Returns package name on module name mapping.
  760. *
  761. * @return array
  762. * @throws \Exception
  763. */
  764. private static function getPackageModuleMapping(): array
  765. {
  766. $jsonFiles = Files::init()->getComposerFiles(ComponentRegistrar::MODULE, false);
  767. $packageModuleMapping = [];
  768. foreach ($jsonFiles as $file) {
  769. $contents = file_get_contents($file);
  770. $composerJson = json_decode($contents);
  771. if (null == $composerJson) {
  772. throw new \Exception("Invalid Json: $file");
  773. }
  774. $moduleXml = simplexml_load_file(dirname($file) . '/etc/module.xml');
  775. $moduleName = str_replace('_', '\\', (string)$moduleXml->module->attributes()->name);
  776. $packageName = $composerJson->name;
  777. $packageModuleMapping[$packageName] = $moduleName;
  778. }
  779. return $packageModuleMapping;
  780. }
  781. /**
  782. * Retrieve array of dependency items
  783. *
  784. * @param $module
  785. * @param $type
  786. * @param $mapType
  787. * @return array
  788. */
  789. protected function _getDependencies($module, $type, $mapType)
  790. {
  791. if (isset(self::$mapDependencies[$module][$type][$mapType])) {
  792. return self::$mapDependencies[$module][$type][$mapType];
  793. }
  794. return [];
  795. }
  796. /**
  797. * Set dependency map items
  798. *
  799. * @param $module
  800. * @param $type
  801. * @param $mapType
  802. * @param $dependencies
  803. */
  804. protected function _setDependencies($module, $type, $mapType, $dependencies)
  805. {
  806. if (!is_array($dependencies)) {
  807. $dependencies = [$dependencies];
  808. }
  809. if (isset(self::$mapDependencies[$module][$type][$mapType])) {
  810. self::$mapDependencies[$module][$type][$mapType] = $dependencies;
  811. }
  812. }
  813. /**
  814. * Check if module is fake
  815. *
  816. * @param $module
  817. * @return bool
  818. */
  819. protected function _isFake($module)
  820. {
  821. return isset(self::$mapDependencies[$module]) ? false : true;
  822. }
  823. }