init
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
/**
|
||||
* Class provides dependency rule for analytics.xml config file.
|
||||
*/
|
||||
class AnalyticsConfigRule implements RuleInterface
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
if ('config' != $fileType || !preg_match('#.*/analytics\.xml$#', $file)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
if (preg_match_all('#<[customProvider|reportProvider][^>]*class=[\'"]([^\'"]+)[\'"]#i', $contents, $matches)) {
|
||||
$classes = array_pop($matches);
|
||||
foreach ($classes as $class) {
|
||||
$classParts = explode('\\', $class);
|
||||
$module = implode('\\', array_slice($classParts, 0, 2));
|
||||
if (strtolower($currentModule) !== strtolower($module)) {
|
||||
$dependenciesInfo[] = [
|
||||
'modules' => [$module],
|
||||
'type' => RuleInterface::TYPE_HARD,
|
||||
'source' => $file,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* Rule for searching DB dependency
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
/**
|
||||
* Class to get DB dependencies information
|
||||
*/
|
||||
class DbRule implements \Magento\TestFramework\Dependency\RuleInterface
|
||||
{
|
||||
/**
|
||||
* Map of tables and modules
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_moduleTableMap;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $tables
|
||||
*/
|
||||
public function __construct(array $tables)
|
||||
{
|
||||
$this->_moduleTableMap = $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets alien dependencies information for current module by analyzing file's contents
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
if ('php' !== $fileType || !preg_match('#.*/(Setup|Resource|Query)/.*\.php$#', $file)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
$unKnowTables = [];
|
||||
if (preg_match_all('#>gettable(name)?\([\'"]([^\'"]+)[\'"]\)#i', $contents, $matches)) {
|
||||
$tables = array_pop($matches);
|
||||
foreach ($tables as $table) {
|
||||
if (!isset($this->_moduleTableMap[$table])) {
|
||||
$unKnowTables[$file][$table] = $table;
|
||||
continue;
|
||||
}
|
||||
if (strtolower($currentModule) !== strtolower($this->_moduleTableMap[$table])) {
|
||||
$dependenciesInfo[] = [
|
||||
'modules' => [$this->_moduleTableMap[$table]],
|
||||
'type' => \Magento\TestFramework\Dependency\RuleInterface::TYPE_HARD,
|
||||
'source' => $table,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($unKnowTables as $tables) {
|
||||
foreach ($tables as $table) {
|
||||
$dependenciesInfo[] = ['modules' => ['Unknown'], 'source' => $table];
|
||||
}
|
||||
}
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
/**
|
||||
* Rule for searching php file dependency
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
use Magento\Framework\App\Utility\Classes;
|
||||
use Magento\Framework\App\Utility\Files;
|
||||
use Magento\TestFramework\Dependency\VirtualType\VirtualTypeMapper;
|
||||
|
||||
/**
|
||||
* Class provide dependency rule for di.xml config files.
|
||||
*/
|
||||
class DiRule implements RuleInterface
|
||||
{
|
||||
/**
|
||||
* @var VirtualTypeMapper
|
||||
*/
|
||||
private $mapper;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $pattern;
|
||||
|
||||
/**
|
||||
* @param VirtualTypeMapper $mapper
|
||||
*/
|
||||
public function __construct(VirtualTypeMapper $mapper)
|
||||
{
|
||||
$this->mapper = $mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get class name pattern.
|
||||
*
|
||||
* @return string
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function getPattern()
|
||||
{
|
||||
if ($this->pattern === null) {
|
||||
$this->pattern = '~\b(?<class>(?<module>('
|
||||
. implode('[_\\\\]|', Files::init()->getNamespaces())
|
||||
. '[_\\\\])[a-zA-Z0-9]+)[a-zA-Z0-9_\\\\]*)\b~';
|
||||
}
|
||||
|
||||
return $this->pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private static $tagNameMap = [
|
||||
'type' => ['name'],
|
||||
'preference' => [
|
||||
'type',
|
||||
'for'
|
||||
],
|
||||
'plugin' => ['type'],
|
||||
'virtualType' => ['type']
|
||||
];
|
||||
|
||||
/**
|
||||
* Gets alien dependencies information for current module by analyzing file's contents
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
//phpcs:ignore Magento2.Functions.DiscouragedFunction
|
||||
if (pathinfo($file, PATHINFO_BASENAME) !== 'di.xml') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
$scope = $this->mapper->getScopeFromFile($file);
|
||||
foreach ($this->fetchPossibleDependencies($contents) as $type => $deps) {
|
||||
foreach ($deps as $dep) {
|
||||
$dep = $this->mapper->getType($dep, $scope);
|
||||
if (preg_match($this->getPattern(), $dep, $matches)) {
|
||||
$referenceModule = str_replace('_', '\\', $matches['module']);
|
||||
if ($currentModule === $referenceModule) {
|
||||
continue;
|
||||
}
|
||||
$dependenciesInfo[] = [
|
||||
'modules' => [$referenceModule],
|
||||
'type' => $type,
|
||||
'source' => $matches['class'],
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all possible dependencies.
|
||||
*
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
private function fetchPossibleDependencies($contents)
|
||||
{
|
||||
$doc = new \DOMDocument();
|
||||
$doc->loadXML($contents);
|
||||
return [
|
||||
RuleInterface::TYPE_SOFT => $this->getSoftDependencies($doc),
|
||||
RuleInterface::TYPE_HARD => $this->getHardDependencies($doc)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect soft dependencies.
|
||||
*
|
||||
* @param \DOMDocument $doc
|
||||
* @return array
|
||||
*/
|
||||
private function getSoftDependencies(\DOMDocument $doc)
|
||||
{
|
||||
$result = [];
|
||||
foreach (self::$tagNameMap as $tagName => $attributeNames) {
|
||||
$nodes = $doc->getElementsByTagName($tagName);
|
||||
/** @var \DOMElement $node */
|
||||
foreach ($nodes as $node) {
|
||||
if ($tagName === 'virtualType' && !$node->getAttribute('type')) {
|
||||
$result[] = Classes::resolveVirtualType($node->getAttribute('name'));
|
||||
continue;
|
||||
}
|
||||
foreach ($attributeNames as $attributeName) {
|
||||
$result[] = $node->getAttribute($attributeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect hard dependencies.
|
||||
*
|
||||
* @param \DOMDocument $doc
|
||||
* @return array
|
||||
*/
|
||||
private function getHardDependencies(\DOMDocument $doc)
|
||||
{
|
||||
$result = [];
|
||||
$xpath = new \DOMXPath($doc);
|
||||
$textNodes = $xpath->query('//*[@xsi:type="object"]');
|
||||
/** @var \DOMElement $node */
|
||||
foreach ($textNodes as $node) {
|
||||
$result[] = $node->nodeValue;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
<?php
|
||||
/**
|
||||
* Rule for searching dependencies in layout files
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
class LayoutRule implements \Magento\TestFramework\Dependency\RuleInterface
|
||||
{
|
||||
/**
|
||||
* Default modules list.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultModules = [
|
||||
'frontend' => 'Magento\Theme',
|
||||
'adminhtml' => 'Magento\Adminhtml',
|
||||
];
|
||||
|
||||
/**
|
||||
* Namespaces to analyze
|
||||
*
|
||||
* Format: {Namespace}|{Namespace}|...
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $_namespaces;
|
||||
|
||||
/**
|
||||
* List of routers
|
||||
*
|
||||
* Format: array(
|
||||
* '{Router}' => '{Module_Name}'
|
||||
* )
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_mapRouters = [];
|
||||
|
||||
/**
|
||||
* List of layout blocks
|
||||
*
|
||||
* Format: array(
|
||||
* '{Area}' => array(
|
||||
* '{Block_Name}' => array('{Module_Name}' => '{Module_Name}')
|
||||
* ))
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_mapLayoutBlocks = [];
|
||||
|
||||
/**
|
||||
* List of layout handles
|
||||
*
|
||||
* Format: array(
|
||||
* '{Area}' => array(
|
||||
* '{Handle_Name}' => array('{Module_Name}' => '{Module_Name}')
|
||||
* ))
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_mapLayoutHandles = [];
|
||||
|
||||
/**
|
||||
* Unknown layout handle
|
||||
*/
|
||||
const EXCEPTION_TYPE_UNKNOWN_HANDLE = 'UNKNOWN_HANDLE';
|
||||
|
||||
/**
|
||||
* Unknown layout block
|
||||
*/
|
||||
const EXCEPTION_TYPE_UNKNOWN_BLOCK = 'UNKNOWN_BLOCK';
|
||||
|
||||
/**
|
||||
* Undefined dependency
|
||||
*/
|
||||
const EXCEPTION_TYPE_UNDEFINED_DEPENDENCY = 'UNDEFINED_DEPENDENCY';
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $mapRouters
|
||||
* @param array $mapLayoutBlocks
|
||||
* @param array $mapLayoutHandles
|
||||
*/
|
||||
public function __construct(array $mapRouters, array $mapLayoutBlocks, array $mapLayoutHandles)
|
||||
{
|
||||
$this->_mapRouters = $mapRouters;
|
||||
$this->_mapLayoutBlocks = $mapLayoutBlocks;
|
||||
$this->_mapLayoutHandles = $mapLayoutHandles;
|
||||
$this->_namespaces = implode('|', \Magento\Framework\App\Utility\Files::init()->getNamespaces());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve dependencies information for current module
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
if ('layout' != $fileType) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$attributes = $this->_caseAttributeModule($currentModule, $contents);
|
||||
$blocks = $this->_caseElementBlock($currentModule, $contents);
|
||||
$actions = $this->_caseElementAction($currentModule, $contents);
|
||||
$handle = $this->_caseLayoutHandle($currentModule, $file, $contents);
|
||||
$handleParents = $this->_caseLayoutHandleParent($currentModule, $file, $contents);
|
||||
$handleUpdates = $this->_caseLayoutHandleUpdate($currentModule, $file, $contents);
|
||||
$references = $this->_caseLayoutReference($currentModule, $file, $contents);
|
||||
|
||||
$dependencies = array_merge(
|
||||
$attributes,
|
||||
$blocks,
|
||||
$actions,
|
||||
$handle,
|
||||
$handleParents,
|
||||
$handleUpdates,
|
||||
$references
|
||||
);
|
||||
return $dependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check dependencies for 'module' attribute
|
||||
*
|
||||
* Ex.: <element module="{module}">
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseAttributeModule($currentModule, &$contents)
|
||||
{
|
||||
$patterns = [
|
||||
'/(?<source><.+module\s*=\s*[\'"](?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)[\'"].*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
];
|
||||
return $this->_checkDependenciesByRegexp($currentModule, $contents, $patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check dependencies for <block> element
|
||||
*
|
||||
* Ex.: <block class="{name}">
|
||||
* <block template="{path}">
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseElementBlock($currentModule, &$contents)
|
||||
{
|
||||
$patterns = [
|
||||
'/(?<source><block.*class\s*=\s*[\'"](?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)[_\\\\]' .
|
||||
'(?:[A-Z][a-zA-Z]+[_\\\\]?){1,}[\'"].*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_HARD,
|
||||
'/(?<source><block.*template\s*=\s*[\'"](?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)::[\w\/\.]+[\'"].*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
];
|
||||
return $this->_checkDependenciesByRegexp($currentModule, $contents, $patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check dependencies for <action> element
|
||||
*
|
||||
* Ex.: <block>{name}
|
||||
* <template>{path}
|
||||
* <file>{path}
|
||||
* <element helper="{name}">
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseElementAction($currentModule, &$contents)
|
||||
{
|
||||
$patterns = [
|
||||
'/(?<source><block\s*>(?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)[_\\\\]' .
|
||||
'(?:[A-Z][a-zA-Z]+[_\\\\]?){1,}<\/block\s*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'/(?<source><template\s*>(?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)::[\w\/\.]+' .
|
||||
'<\/template\s*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'/(?<source><file\s*>(?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)::[\w\/\.-]+' .
|
||||
'<\/file\s*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'/(?<source><.*helper\s*=\s*[\'"](?<namespace>' .
|
||||
$this->_namespaces .
|
||||
')[_\\\\]' .
|
||||
'(?<module>[A-Z][a-zA-Z]+)[_\\\\](?:[A-Z][a-z]+[_\\\\]?){1,}::[\w]+' .
|
||||
'[\'"].*>)/' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
];
|
||||
return $this->_checkDependenciesByRegexp($currentModule, $contents, $patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout handles
|
||||
*
|
||||
* Ex.: <layout><{name}>...</layout>
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseLayoutHandle($currentModule, $file, &$contents)
|
||||
{
|
||||
$xml = simplexml_load_string($contents);
|
||||
if (!$xml) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$area = $this->_getAreaByFile($file);
|
||||
|
||||
$result = [];
|
||||
foreach ((array)$xml->xpath('/layout/child::*') as $element) {
|
||||
$check = $this->_checkDependencyLayoutHandle($currentModule, $area, $element->getName());
|
||||
$modules = isset($check['modules']) ? $check['modules'] : null;
|
||||
if ($modules) {
|
||||
foreach ($modules as $module) {
|
||||
$result[$module] = [
|
||||
'type' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'source' => $element->getName(),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout handles parents
|
||||
*
|
||||
* Ex.: <layout_name parent="{name}">
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseLayoutHandleParent($currentModule, $file, &$contents)
|
||||
{
|
||||
$xml = simplexml_load_string($contents);
|
||||
if (!$xml) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$area = $this->_getAreaByFile($file);
|
||||
|
||||
$result = [];
|
||||
foreach ((array)$xml->xpath('/layout/child::*/@parent') as $element) {
|
||||
$check = $this->_checkDependencyLayoutHandle($currentModule, $area, (string)$element);
|
||||
$modules = isset($check['modules']) ? $check['modules'] : null;
|
||||
if ($modules) {
|
||||
foreach ($modules as $module) {
|
||||
$result[$module] = [
|
||||
'type' => \Magento\Test\Integrity\DependencyTest::TYPE_HARD,
|
||||
'source' => (string)$element,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout handles updates
|
||||
*
|
||||
* Ex.: <update handle="{name}" />
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseLayoutHandleUpdate($currentModule, $file, &$contents)
|
||||
{
|
||||
$xml = simplexml_load_string($contents);
|
||||
if (!$xml) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$area = $this->_getAreaByFile($file);
|
||||
|
||||
$result = [];
|
||||
foreach ((array)$xml->xpath('//update/@handle') as $element) {
|
||||
$check = $this->_checkDependencyLayoutHandle($currentModule, $area, (string)$element);
|
||||
$modules = isset($check['modules']) ? $check['modules'] : null;
|
||||
if ($modules) {
|
||||
foreach ($modules as $module) {
|
||||
$result[$module] = [
|
||||
'type' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'source' => (string)$element,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout references
|
||||
*
|
||||
* Ex.: <reference name="{name}">
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseLayoutReference($currentModule, $file, &$contents)
|
||||
{
|
||||
$xml = simplexml_load_string($contents);
|
||||
if (!$xml) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$area = $this->_getAreaByFile($file);
|
||||
|
||||
$result = [];
|
||||
foreach ((array)$xml->xpath('//reference/@name') as $element) {
|
||||
$check = $this->_checkDependencyLayoutBlock($currentModule, $area, (string)$element);
|
||||
$modules = isset($check['modules']) ? $check['modules'] : null;
|
||||
if ($modules) {
|
||||
foreach ($modules as $module) {
|
||||
$result[$module] = [
|
||||
'type' => \Magento\Test\Integrity\DependencyTest::TYPE_SOFT,
|
||||
'source' => (string)$element,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search dependencies by defined regexp patterns
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $contents
|
||||
* @param array $patterns
|
||||
* @return array
|
||||
*/
|
||||
protected function _checkDependenciesByRegexp($currentModule, &$contents, $patterns = [])
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($patterns as $pattern => $type) {
|
||||
if (preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER)) {
|
||||
foreach ($matches as $match) {
|
||||
$module = $match['namespace'] . '\\' . $match['module'];
|
||||
|
||||
if ($currentModule != $module) {
|
||||
$result[$module] = ['type' => $type, 'source' => $match['source']];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout handle dependency
|
||||
*
|
||||
* Return: array(
|
||||
* 'modules' // dependent modules
|
||||
* 'source' // source text
|
||||
* )
|
||||
*
|
||||
* @param admin $currentModule
|
||||
* @param string $area
|
||||
* @param string $handle
|
||||
* @return string[]
|
||||
*/
|
||||
protected function _checkDependencyLayoutHandle($currentModule, $area, $handle)
|
||||
{
|
||||
$chunks = explode('_', $handle);
|
||||
if (count($chunks) > 1) {
|
||||
// Remove 'action' part from handle name
|
||||
array_pop($chunks);
|
||||
}
|
||||
$router = implode('_', $chunks);
|
||||
if (isset($this->_mapRouters[$router])) {
|
||||
// CASE 1: Single dependency
|
||||
$modules = $this->_mapRouters[$router];
|
||||
if (!in_array($currentModule, $modules)) {
|
||||
return ['modules' => $modules];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($this->_mapLayoutHandles[$area][$handle])) {
|
||||
// CASE 2: No dependencies
|
||||
$modules = $this->_mapLayoutHandles[$area][$handle];
|
||||
if (isset($modules[$currentModule])) {
|
||||
return ['modules' => []];
|
||||
}
|
||||
|
||||
// CASE 3: Single dependency
|
||||
if (1 == count($modules)) {
|
||||
return ['modules' => $modules];
|
||||
}
|
||||
|
||||
// CASE 4: Default module dependency
|
||||
$defaultModule = $this->_getDefaultModuleName($area);
|
||||
if (isset($modules[$defaultModule])) {
|
||||
return ['modules' => [$defaultModule]];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout block dependency
|
||||
*
|
||||
* Return: array(
|
||||
* 'modules' // dependent modules
|
||||
* 'source' // source text
|
||||
* )
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $area
|
||||
* @param string $block
|
||||
* @return string[]
|
||||
*/
|
||||
protected function _checkDependencyLayoutBlock($currentModule, $area, $block)
|
||||
{
|
||||
if (isset($this->_mapLayoutBlocks[$area][$block])) {
|
||||
// CASE 1: No dependencies
|
||||
$modules = $this->_mapLayoutBlocks[$area][$block];
|
||||
if (isset($modules[$currentModule])) {
|
||||
return ['modules' => []];
|
||||
}
|
||||
|
||||
// CASE 2: Single dependency
|
||||
if (1 == count($modules)) {
|
||||
return ['modules' => $modules];
|
||||
}
|
||||
|
||||
// CASE 3: Default module dependency
|
||||
$defaultModule = $this->_getDefaultModuleName($area);
|
||||
if (isset($modules[$defaultModule])) {
|
||||
return ['modules' => [$defaultModule]];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get area from file path
|
||||
*
|
||||
* @param string $file
|
||||
* @return string
|
||||
*/
|
||||
protected function _getAreaByFile($file)
|
||||
{
|
||||
$area = 'default';
|
||||
if (preg_match('/\/(?<area>adminhtml|frontend)\//', $file, $matches)) {
|
||||
$area = $matches['area'];
|
||||
}
|
||||
return $area;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve unique dependencies
|
||||
*
|
||||
* @param array $dependencies
|
||||
* @return array
|
||||
*/
|
||||
protected function _getUniqueDependencies($dependencies = [])
|
||||
{
|
||||
$result = [];
|
||||
foreach ($dependencies as $module => $value) {
|
||||
$result[] = ['modules' => [$module], 'type' => $value['type'], 'source' => $value['source']];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve default module name (by area)
|
||||
*
|
||||
* @param string $area
|
||||
* @return string|null
|
||||
*/
|
||||
protected function _getDefaultModuleName($area = 'default')
|
||||
{
|
||||
if (isset($this->_defaultModules[$area])) {
|
||||
return $this->_defaultModules[$area];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
use Magento\Framework\App\Utility\Files;
|
||||
use Magento\Framework\Config\Reader\Filesystem as ConfigReader;
|
||||
use Magento\Framework\Exception\ConfigurationMismatchException;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\TestFramework\Dependency\Reader\ClassScanner;
|
||||
use Magento\TestFramework\Dependency\Route\RouteMapper;
|
||||
use Magento\TestFramework\Exception\NoSuchActionException;
|
||||
use Magento\TestFramework\Inspection\Exception;
|
||||
|
||||
/**
|
||||
* Rule to check the dependencies between modules based on references, getUrl and layout blocks
|
||||
*/
|
||||
class PhpRule implements RuleInterface
|
||||
{
|
||||
/**
|
||||
* List of filepaths for DI files
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $diFiles;
|
||||
|
||||
/**
|
||||
* Map from plugin classes to the subjects they modify
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $pluginMap;
|
||||
|
||||
/**
|
||||
* List of routers
|
||||
*
|
||||
* Format: array(
|
||||
* '{Router}' => '{Module_Name}'
|
||||
* )
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $_mapRouters = [];
|
||||
|
||||
/**
|
||||
* List of layout blocks
|
||||
*
|
||||
* Format: array(
|
||||
* '{Area}' => array(
|
||||
* '{Block_Name}' => array('{Module_Name}' => '{Module_Name}')
|
||||
* ))
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_mapLayoutBlocks = [];
|
||||
|
||||
/**
|
||||
* Used to retrieve information from WebApi urls
|
||||
* @var ConfigReader
|
||||
*/
|
||||
protected $configReader;
|
||||
|
||||
/**
|
||||
* Default modules list.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultModules = [
|
||||
'frontend' => 'Magento\Theme',
|
||||
'adminhtml' => 'Magento\Adminhtml',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var RouteMapper
|
||||
*/
|
||||
private $routeMapper;
|
||||
|
||||
/**
|
||||
* Whitelists for dependency check
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $whitelists;
|
||||
|
||||
/**
|
||||
* @var ClassScanner
|
||||
*/
|
||||
private $classScanner;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $serviceMethods;
|
||||
|
||||
/**
|
||||
* @param array $mapRouters
|
||||
* @param array $mapLayoutBlocks
|
||||
* @param ConfigReader $configReader
|
||||
* @param array $pluginMap
|
||||
* @param array $whitelists
|
||||
* @param ClassScanner|null $classScanner
|
||||
* @param RouteMapper|null $routeMapper
|
||||
*/
|
||||
public function __construct(
|
||||
array $mapRouters,
|
||||
array $mapLayoutBlocks,
|
||||
ConfigReader $configReader,
|
||||
array $pluginMap = [],
|
||||
array $whitelists = [],
|
||||
ClassScanner $classScanner = null,
|
||||
RouteMapper $routeMapper = null
|
||||
) {
|
||||
$this->_mapRouters = $mapRouters;
|
||||
$this->_mapLayoutBlocks = $mapLayoutBlocks;
|
||||
$this->configReader = $configReader;
|
||||
$this->pluginMap = $pluginMap ?: null;
|
||||
$this->whitelists = $whitelists;
|
||||
$this->classScanner = $classScanner ?? new ClassScanner();
|
||||
$this->routeMapper = $routeMapper ?? new RouteMapper();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets alien dependencies information for current module by analyzing file's contents
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
if (!in_array($fileType, ['php', 'template', 'fixture'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
$dependenciesInfo = $this->considerCaseDependencies(
|
||||
$dependenciesInfo,
|
||||
$this->caseClassesAndIdentifiers($currentModule, $file, $contents)
|
||||
);
|
||||
$dependenciesInfo = $this->considerCaseDependencies(
|
||||
$dependenciesInfo,
|
||||
$this->_caseGetUrl($currentModule, $contents, $file)
|
||||
);
|
||||
$dependenciesInfo = $this->considerCaseDependencies(
|
||||
$dependenciesInfo,
|
||||
$this->_caseLayoutBlock($currentModule, $fileType, $file, $contents)
|
||||
);
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get routes whitelist
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getRoutesWhitelist(): array
|
||||
{
|
||||
return $this->whitelists['routes'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check references to classes and identifiers defined in other modules
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function caseClassesAndIdentifiers($currentModule, $file, &$contents)
|
||||
{
|
||||
$pattern = '~\b(?<class>(?<module>('
|
||||
. implode(
|
||||
'[_\\\\]|',
|
||||
Files::init()->getNamespaces()
|
||||
)
|
||||
. '(?<delimiter>[_\\\\]))[a-zA-Z0-9]{2,})'
|
||||
. '(?<class_inside_module>\\4[a-zA-Z0-9_\\\\]{2,})?)\b'
|
||||
. '(?:::(?<module_scoped_key>[A-Za-z0-9_/.]+)[\'"])?~';
|
||||
|
||||
if (!preg_match_all($pattern, $contents, $matches)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
$matches['module'] = array_unique($matches['module']);
|
||||
foreach ($matches['module'] as $i => $referenceModule) {
|
||||
$referenceModule = str_replace('_', '\\', $referenceModule);
|
||||
if ($currentModule == $referenceModule) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$dependencyClass = trim($matches['class'][$i]);
|
||||
if (empty($matches['class_inside_module'][$i]) && !empty($matches['module_scoped_key'][$i])) {
|
||||
$dependencyType = RuleInterface::TYPE_SOFT;
|
||||
} else {
|
||||
$currentClass = $this->getClassFromFilepath($file);
|
||||
$dependencyType = $this->isPluginDependency($currentClass, $dependencyClass)
|
||||
? RuleInterface::TYPE_SOFT
|
||||
: RuleInterface::TYPE_HARD;
|
||||
}
|
||||
|
||||
$dependenciesInfo[] = [
|
||||
'modules' => [$referenceModule],
|
||||
'type' => $dependencyType,
|
||||
'source' => $dependencyClass,
|
||||
];
|
||||
}
|
||||
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get class name from filename based on class/file naming conventions
|
||||
*
|
||||
* @param string $filepath
|
||||
* @return string
|
||||
*/
|
||||
private function getClassFromFilepath(string $filepath): string
|
||||
{
|
||||
return $this->classScanner->getClassName($filepath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load DI configuration files
|
||||
*
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function loadDiFiles()
|
||||
{
|
||||
if (!$this->diFiles) {
|
||||
$this->diFiles = Files::init()->getDiConfigs();
|
||||
}
|
||||
return $this->diFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an array of plugin info
|
||||
*
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function loadPluginMap()
|
||||
{
|
||||
if (!$this->pluginMap) {
|
||||
foreach ($this->loadDiFiles() as $filepath) {
|
||||
$dom = new \DOMDocument();
|
||||
// phpcs:ignore Magento2.Functions.DiscouragedFunction
|
||||
$dom->loadXML(file_get_contents($filepath));
|
||||
$typeNodes = $dom->getElementsByTagName('type');
|
||||
/** @var \DOMElement $type */
|
||||
foreach ($typeNodes as $type) {
|
||||
/** @var \DOMElement $plugin */
|
||||
foreach ($type->getElementsByTagName('plugin') as $plugin) {
|
||||
$subject = $type->getAttribute('name');
|
||||
$pluginType = $plugin->getAttribute('type');
|
||||
$this->pluginMap[$pluginType] = $subject;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->pluginMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a the dependency relation is because of a plugin
|
||||
*
|
||||
* True IFF the dependent is a plugin for some class in the same module as the dependency.
|
||||
*
|
||||
* @param string $dependent
|
||||
* @param string $dependency
|
||||
* @return bool
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function isPluginDependency($dependent, $dependency)
|
||||
{
|
||||
$pluginMap = $this->loadPluginMap();
|
||||
$subject = isset($pluginMap[$dependent])
|
||||
? $pluginMap[$dependent]
|
||||
: null;
|
||||
if ($subject === $dependency) {
|
||||
return true;
|
||||
} elseif ($subject) {
|
||||
$moduleNameLength = strpos($subject, '\\', strpos($subject, '\\') + 1);
|
||||
$subjectModule = substr($subject, 0, $moduleNameLength);
|
||||
return strpos($dependency, $subjectModule) === 0;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check get URL method
|
||||
*
|
||||
* Ex.: getUrl('{path}')
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $contents
|
||||
* @param string $file
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function _caseGetUrl(string $currentModule, string &$contents, string $file): array
|
||||
{
|
||||
$dependencies = [];
|
||||
$pattern = '#(\->|:)(?<source>getUrl\(([\'"])(?<path>[a-zA-Z0-9\-_*/]+)\3)\s*[,)]#';
|
||||
if (!preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER)) {
|
||||
return $dependencies;
|
||||
}
|
||||
try {
|
||||
foreach ($matches as $item) {
|
||||
$path = $item['path'];
|
||||
$modules = [];
|
||||
if (strpos($path, '*') !== false) {
|
||||
$modules = $this->processWildcardUrl($path, $file);
|
||||
} elseif (preg_match('#rest(?<service>/V1/.+)#i', $path, $apiMatch)) {
|
||||
$modules = $this->processApiUrl($apiMatch['service']);
|
||||
} else {
|
||||
$modules = $this->processStandardUrl($path);
|
||||
}
|
||||
if ($modules && !in_array($currentModule, $modules)) {
|
||||
$dependencies[] = [
|
||||
'modules' => $modules,
|
||||
'type' => RuleInterface::TYPE_HARD,
|
||||
'source' => $item['source'],
|
||||
];
|
||||
}
|
||||
}
|
||||
} catch (NoSuchActionException $e) {
|
||||
if (array_search($e->getMessage(), $this->getRoutesWhitelist()) === false) {
|
||||
throw new LocalizedException(__('Invalid URL path: %1', $e->getMessage()), $e);
|
||||
}
|
||||
}
|
||||
return $dependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to get module dependencies used by a wildcard Url
|
||||
*
|
||||
* @param string $urlPath
|
||||
* @param string $filePath
|
||||
* @return string[]
|
||||
* @throws NoSuchActionException
|
||||
*/
|
||||
private function processWildcardUrl(string $urlPath, string $filePath)
|
||||
{
|
||||
$filePath = strtolower($filePath);
|
||||
$urlRoutePieces = explode('/', $urlPath);
|
||||
$routeId = array_shift($urlRoutePieces);
|
||||
//Skip route wildcard processing as this requires using the routeMapper
|
||||
if ('*' === $routeId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Only handle Controllers. ie: Ignore Blocks, Templates, and Models due to complexity in static resolution
|
||||
* of route
|
||||
*/
|
||||
if (!preg_match(
|
||||
'#controller/(adminhtml/)?(?<controller_name>.+)/(?<action_name>\w+).php$#',
|
||||
$filePath,
|
||||
$fileParts
|
||||
)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$controllerName = array_shift($urlRoutePieces);
|
||||
if ('*' === $controllerName) {
|
||||
$controllerName = str_replace('/', '_', $fileParts['controller_name']);
|
||||
}
|
||||
|
||||
if (empty($urlRoutePieces) || !$urlRoutePieces[0]) {
|
||||
$actionName = UrlInterface::DEFAULT_ACTION_NAME;
|
||||
} else {
|
||||
$actionName = array_shift($urlRoutePieces);
|
||||
if ('*' === $actionName) {
|
||||
$actionName = $fileParts['action_name'];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->routeMapper->getDependencyByRoutePath(
|
||||
strtolower($routeId),
|
||||
strtolower($controllerName),
|
||||
strtolower($actionName)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to get module dependencies used by a standard URL
|
||||
*
|
||||
* @param string $path
|
||||
* @return string[]
|
||||
* @throws NoSuchActionException
|
||||
*/
|
||||
private function processStandardUrl(string $path)
|
||||
{
|
||||
$pattern = '#(?<route_id>[a-z0-9\-_]{3,})'
|
||||
. '(/(?<controller_name>[a-z0-9\-_]+))?(/(?<action_name>[a-z0-9\-_]+))?#i';
|
||||
if (!preg_match($pattern, $path, $match)) {
|
||||
throw new NoSuchActionException('Failed to parse standard url path: ' . $path);
|
||||
}
|
||||
$routeId = $match['route_id'];
|
||||
$controllerName = $match['controller_name'] ?? UrlInterface::DEFAULT_CONTROLLER_NAME;
|
||||
$actionName = $match['action_name'] ?? UrlInterface::DEFAULT_ACTION_NAME;
|
||||
|
||||
return $this->routeMapper->getDependencyByRoutePath(
|
||||
$routeId,
|
||||
$controllerName,
|
||||
$actionName
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create regex patterns from service url paths
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getServiceMethodRegexps(): array
|
||||
{
|
||||
if (!$this->serviceMethods) {
|
||||
$this->serviceMethods = [];
|
||||
$serviceRoutes = $this->configReader->read()['routes'];
|
||||
foreach ($serviceRoutes as $serviceRouteUrl => $methods) {
|
||||
$pattern = '#:\w+#';
|
||||
$replace = '\w+';
|
||||
$serviceRouteUrlRegex = preg_replace($pattern, $replace, $serviceRouteUrl);
|
||||
$serviceRouteUrlRegex = '#^' . $serviceRouteUrlRegex . '$#';
|
||||
$this->serviceMethods[$serviceRouteUrlRegex] = $methods;
|
||||
}
|
||||
}
|
||||
return $this->serviceMethods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to get module dependencies used by an API URL
|
||||
*
|
||||
* @param string $path
|
||||
* @return string[]
|
||||
*
|
||||
* @throws NoSuchActionException
|
||||
* @throws Exception
|
||||
*/
|
||||
private function processApiUrl(string $path): array
|
||||
{
|
||||
foreach ($this->getServiceMethodRegexps() as $serviceRouteUrlRegex => $methods) {
|
||||
/**
|
||||
* Since we expect that every service method should be within the same module, we can use the class from
|
||||
* any method
|
||||
*/
|
||||
if (preg_match($serviceRouteUrlRegex, $path)) {
|
||||
$method = reset($methods);
|
||||
|
||||
$className = $method['service']['class'];
|
||||
//get module from className
|
||||
if (preg_match('#^(?<module>\w+[\\\]\w+)#', $className, $match)) {
|
||||
return [$match['module']];
|
||||
}
|
||||
throw new Exception('Failed to parse class from className: ' . $className);
|
||||
}
|
||||
}
|
||||
throw new NoSuchActionException('Failed to match service with url path: ' . $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout blocks
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
protected function _caseLayoutBlock(string $currentModule, string $fileType, string $file, string &$contents): array
|
||||
{
|
||||
$pattern = '/[\->:]+(?<source>(?:getBlock|getBlockHtml)\([\'"](?<block>[\w\.\-]+)[\'"]\))/';
|
||||
|
||||
$area = $this->_getAreaByFile($file, $fileType);
|
||||
|
||||
$result = [];
|
||||
if (!preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach ($matches as $match) {
|
||||
if (in_array($match['block'], ['root', 'content'])) {
|
||||
continue;
|
||||
}
|
||||
$check = $this->_checkDependencyLayoutBlock($currentModule, $area, $match['block']);
|
||||
$modules = isset($check['modules']) ? $check['modules'] : null;
|
||||
if ($modules) {
|
||||
foreach ($modules as $module) {
|
||||
$result[$module] = [
|
||||
'type' => RuleInterface::TYPE_HARD,
|
||||
'source' => $match['source'],
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->_getUniqueDependencies($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get area from file path
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $fileType
|
||||
* @return string|null
|
||||
*/
|
||||
protected function _getAreaByFile(string $file, string $fileType): ?string
|
||||
{
|
||||
if ($fileType == 'php') {
|
||||
return null;
|
||||
}
|
||||
$area = 'default';
|
||||
if (preg_match('/\/(?<area>adminhtml|frontend)\//', $file, $matches)) {
|
||||
$area = $matches['area'];
|
||||
}
|
||||
return $area;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check layout block dependency
|
||||
*
|
||||
* Return: array(
|
||||
* 'modules' // dependent modules
|
||||
* 'source' // source text
|
||||
* )
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string|null $area
|
||||
* @param string $block
|
||||
* @return array
|
||||
*/
|
||||
protected function _checkDependencyLayoutBlock(string $currentModule, ?string $area, string $block): array
|
||||
{
|
||||
if (isset($this->_mapLayoutBlocks[$area][$block]) || $area === null) {
|
||||
// CASE 1: No dependencies
|
||||
$modules = [];
|
||||
if ($area === null) {
|
||||
foreach ($this->_mapLayoutBlocks as $blocks) {
|
||||
if (array_key_exists($block, $blocks)) {
|
||||
$modules += $blocks[$block];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$modules = $this->_mapLayoutBlocks[$area][$block];
|
||||
}
|
||||
if (isset($modules[$currentModule])) {
|
||||
return ['modules' => []];
|
||||
}
|
||||
// CASE 2: Single dependency
|
||||
if (1 == count($modules)) {
|
||||
return ['modules' => $modules];
|
||||
}
|
||||
// CASE 3: Default module dependency
|
||||
$defaultModule = $this->_getDefaultModuleName($area);
|
||||
if (isset($modules[$defaultModule])) {
|
||||
return ['modules' => [$defaultModule]];
|
||||
}
|
||||
}
|
||||
// CASE 4: \Exception - Undefined block
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve default module name (by area)
|
||||
*
|
||||
* @param string $area
|
||||
* @return null
|
||||
*/
|
||||
protected function _getDefaultModuleName($area = 'default')
|
||||
{
|
||||
if (isset($this->_defaultModules[$area])) {
|
||||
return $this->_defaultModules[$area];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve unique dependencies
|
||||
*
|
||||
* @param array $dependencies
|
||||
* @return array
|
||||
*/
|
||||
protected function _getUniqueDependencies($dependencies = [])
|
||||
{
|
||||
$result = [];
|
||||
foreach ($dependencies as $module => $value) {
|
||||
$result[] = ['modules' => [$module], 'type' => $value['type'], 'source' => $value['source']];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge dependencies
|
||||
*
|
||||
* @param array $known
|
||||
* @param array $new
|
||||
* @return array
|
||||
*/
|
||||
private function considerCaseDependencies($known, $new)
|
||||
{
|
||||
return array_merge($known, $new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Dependency\Reader;
|
||||
|
||||
use Magento\Setup\Module\Di\Code\Reader\FileClassScanner;
|
||||
|
||||
/**
|
||||
* Search classes in file by path.
|
||||
*/
|
||||
class ClassScanner
|
||||
{
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
private $classNames = [];
|
||||
|
||||
/**
|
||||
* Get class name by file name.
|
||||
*
|
||||
* @param string $filePath
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getClassName(string $filePath): string
|
||||
{
|
||||
if (!isset($this->classNames[$filePath])) {
|
||||
$this->classNames[$filePath] = $this->loadClassName($filePath);
|
||||
}
|
||||
|
||||
return $this->classNames[$filePath];
|
||||
}
|
||||
|
||||
/**
|
||||
* Load class name from file.
|
||||
*
|
||||
* @param string $filePath
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function loadClassName(string $filePath): string
|
||||
{
|
||||
$scanner = new FileClassScanner($filePath);
|
||||
return $scanner->getClassName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
/**
|
||||
* Class provides dependency rule for reports.xml config file.
|
||||
*/
|
||||
class ReportsConfigRule implements RuleInterface
|
||||
{
|
||||
/**
|
||||
* Map of tables and modules
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $moduleTableMap;
|
||||
|
||||
/**
|
||||
* @param array $tables
|
||||
*/
|
||||
public function __construct(array $tables)
|
||||
{
|
||||
$this->moduleTableMap = $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents)
|
||||
{
|
||||
if ('config' != $fileType || !preg_match('#.*/reports\.xml$#', $file)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dependenciesInfo = [];
|
||||
if (preg_match_all('#<source[^>]*name=[\'"]([^\'"]+)[\'"]#i', $contents, $matches)) {
|
||||
$tables = array_pop($matches);
|
||||
foreach ($tables as $table) {
|
||||
if (!isset($this->moduleTableMap[$table])) {
|
||||
continue;
|
||||
}
|
||||
if (strtolower($currentModule) !== strtolower($this->moduleTableMap[$table])) {
|
||||
$dependenciesInfo[] = [
|
||||
'modules' => [$this->moduleTableMap[$table]],
|
||||
'type' => RuleInterface::TYPE_HARD,
|
||||
'source' => $table,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $dependenciesInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
<?php
|
||||
/**
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Magento\TestFramework\Dependency\Route;
|
||||
|
||||
use Exception;
|
||||
use Magento\Framework\App\Area;
|
||||
use Magento\Framework\App\Utility\Files;
|
||||
use Magento\Framework\Component\ComponentFile;
|
||||
use Magento\TestFramework\Exception\NoSuchActionException;
|
||||
|
||||
/**
|
||||
* Route mapper based on routes.xml declarations
|
||||
*/
|
||||
class RouteMapper
|
||||
{
|
||||
/**
|
||||
* List of routers
|
||||
*
|
||||
* Format: array(
|
||||
* '{Router_Id}' => '{Route_Id}' => ['{Module_Name}']
|
||||
* )
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $routers = [];
|
||||
|
||||
/**
|
||||
* List of routes.xml files by modules
|
||||
*
|
||||
* Format: array(
|
||||
* '{Module_Name}' => ['{Filename}']
|
||||
* )
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $routeConfigFiles = [];
|
||||
|
||||
/**
|
||||
* List of controllers actions
|
||||
*
|
||||
* Format: array(
|
||||
* '{Router_Id}' => '{Route_Id}' => '{Controller_Name}' => '{Action_Name}' => [{'Module_Name'}]
|
||||
* )
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $actions = [];
|
||||
|
||||
/**
|
||||
* List of reserved words
|
||||
*
|
||||
* @see \Magento\Framework\App\Router\ActionList
|
||||
* @var array
|
||||
*/
|
||||
private $reservedWords = [
|
||||
'abstract' => 1,
|
||||
'and' => 1,
|
||||
'array' => 1,
|
||||
'as' => 1,
|
||||
'break' => 1,
|
||||
'callable' => 1,
|
||||
'case' => 1,
|
||||
'catch' => 1,
|
||||
'class' => 1,
|
||||
'clone' => 1,
|
||||
'const' => 1,
|
||||
'continue' => 1,
|
||||
'declare' => 1,
|
||||
'default' => 1,
|
||||
'die' => 1,
|
||||
'do' => 1,
|
||||
'echo' => 1,
|
||||
'else' => 1,
|
||||
'elseif' => 1,
|
||||
'empty' => 1,
|
||||
'enddeclare' => 1,
|
||||
'endfor' => 1,
|
||||
'endforeach' => 1,
|
||||
'endif' => 1,
|
||||
'endswitch' => 1,
|
||||
'endwhile' => 1,
|
||||
'eval' => 1,
|
||||
'exit' => 1,
|
||||
'extends' => 1,
|
||||
'final' => 1,
|
||||
'finally' => 1,
|
||||
'fn' => 1,
|
||||
'for' => 1,
|
||||
'foreach' => 1,
|
||||
'function' => 1,
|
||||
'global' => 1,
|
||||
'goto' => 1,
|
||||
'if' => 1,
|
||||
'implements' => 1,
|
||||
'include' => 1,
|
||||
'instanceof' => 1,
|
||||
'insteadof' => 1,
|
||||
'interface' => 1,
|
||||
'isset' => 1,
|
||||
'list' => 1,
|
||||
'match' => 1,
|
||||
'namespace' => 1,
|
||||
'new' => 1,
|
||||
'or' => 1,
|
||||
'print' => 1,
|
||||
'private' => 1,
|
||||
'protected' => 1,
|
||||
'public' => 1,
|
||||
'require' => 1,
|
||||
'return' => 1,
|
||||
'static' => 1,
|
||||
'switch' => 1,
|
||||
'throw' => 1,
|
||||
'trait' => 1,
|
||||
'try' => 1,
|
||||
'unset' => 1,
|
||||
'use' => 1,
|
||||
'var' => 1,
|
||||
'void' => 1,
|
||||
'while' => 1,
|
||||
'xor' => 1,
|
||||
'yield' => 1
|
||||
];
|
||||
|
||||
/**
|
||||
* Provide routing declaration by router_id
|
||||
*
|
||||
* @param string $routerId
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getRoutes(string $routerId = ''): array
|
||||
{
|
||||
$routes = [];
|
||||
if (!$routerId) {
|
||||
foreach ($this->getRoutersMap() as $routesByRouterType) {
|
||||
$routes = array_merge_recursive($routes, $routesByRouterType);
|
||||
}
|
||||
array_walk(
|
||||
$routes,
|
||||
function (&$modules) {
|
||||
$modules = array_unique($modules);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$routes = $this->getRoutersMap()[$routerId] ?? [];
|
||||
}
|
||||
return $routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide dependencies for a specific URL path
|
||||
*
|
||||
* @param string $routeId
|
||||
* @param string $controllerName
|
||||
* @param string $actionName
|
||||
* @return string[]
|
||||
* @throws NoSuchActionException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getDependencyByRoutePath(
|
||||
string $routeId,
|
||||
string $controllerName,
|
||||
string $actionName
|
||||
): array {
|
||||
$routeId = strtolower($routeId);
|
||||
$controllerName = strtolower($controllerName);
|
||||
$actionName = strtolower($actionName);
|
||||
|
||||
if (isset($this->reservedWords[$actionName])) {
|
||||
$actionName .= 'action';
|
||||
}
|
||||
|
||||
$dependencies = [];
|
||||
foreach ($this->getRouterTypes() as $routerId) {
|
||||
if (isset($this->getActionsMap()[$routerId][$routeId][$controllerName][$actionName])) {
|
||||
$dependencies[] = $this->getActionsMap()[$routerId][$routeId][$controllerName][$actionName];
|
||||
}
|
||||
}
|
||||
$dependencies = array_merge([], ...$dependencies);
|
||||
|
||||
if (empty($dependencies)) {
|
||||
throw new NoSuchActionException(implode('/', [$routeId, $controllerName, $actionName]));
|
||||
} else {
|
||||
$dependencies = array_unique($dependencies);
|
||||
}
|
||||
return $dependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a list of router type
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getRouterTypes()
|
||||
{
|
||||
return array_keys($this->getActionsMap());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide routing declaration
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getRoutersMap()
|
||||
{
|
||||
if (empty($this->routers)) {
|
||||
foreach ($this->getListRoutesXml() as $module => $configFiles) {
|
||||
foreach ($configFiles as $configFile) {
|
||||
$this->processConfigFile($module, $configFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->routers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update routers map for the module basing on the routing config file
|
||||
*
|
||||
* @param string $module
|
||||
* @param string $configFile
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function processConfigFile(string $module, string $configFile)
|
||||
{
|
||||
// Read module's routes.xml file
|
||||
$config = simplexml_load_file($configFile);
|
||||
|
||||
$routers = $config->xpath("/config/router");
|
||||
foreach ($routers as $router) {
|
||||
$routerId = (string)$router['id'];
|
||||
foreach ($router->xpath('route') as $route) {
|
||||
$routeId = (string)$route['id'];
|
||||
if (!isset($this->routers[$routerId][$routeId])) {
|
||||
$this->routers[$routerId][$routeId] = [];
|
||||
}
|
||||
if (!in_array($module, $this->routers[$routerId][$routeId])) {
|
||||
$this->routers[$routerId][$routeId][] = $module;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the list of routes.xml files (by modules)
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getListRoutesXml()
|
||||
{
|
||||
if (empty($this->routeConfigFiles)) {
|
||||
$files = Files::init()->getConfigFiles('*/routes.xml', [], false, true);
|
||||
/** @var ComponentFile $componentFile */
|
||||
foreach ($files as $componentFile) {
|
||||
$module = str_replace('_', '\\', $componentFile->getComponentName());
|
||||
$this->routeConfigFiles[$module][] = $componentFile->getFullPath();
|
||||
}
|
||||
}
|
||||
return $this->routeConfigFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a list of available actions
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getActionsMap(): array
|
||||
{
|
||||
if (empty($this->actions)) {
|
||||
$files = Files::init()->getPhpFiles(Files::INCLUDE_APP_CODE);
|
||||
$actionsMap = [];
|
||||
foreach ($this->getRoutersMap() as $routerId => $routes) {
|
||||
$actionsMapPerArea = [];
|
||||
foreach ($routes as $routeId => $dependencies) {
|
||||
$actionsMapPerArea[$routeId] = [];
|
||||
foreach ($dependencies as $module) {
|
||||
$moduleActions = $this->getModuleActionsMapping($module, $routerId, $files);
|
||||
$actionsMapPerArea[$routeId] =
|
||||
array_merge_recursive($actionsMapPerArea[$routeId], $moduleActions);
|
||||
}
|
||||
}
|
||||
$actionsMap[$routerId] = $actionsMapPerArea;
|
||||
}
|
||||
$this->actions = $actionsMap;
|
||||
}
|
||||
|
||||
return $this->actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a list of available module actions by router_id
|
||||
*
|
||||
* @param string $module
|
||||
* @param string $routerId
|
||||
* @param array $files
|
||||
* @return array
|
||||
*/
|
||||
private function getModuleActionsMapping(string $module, string $routerId, array $files): array
|
||||
{
|
||||
$subdirectoryPattern = str_replace('\\', DIRECTORY_SEPARATOR, $module);
|
||||
$subdirectoryPattern .= DIRECTORY_SEPARATOR . 'Controller/';
|
||||
if (array_search($routerId, [Area::AREA_ADMINHTML, Area::AREA_ADMIN], true) !== false) {
|
||||
$subdirectoryPattern .= ucfirst(Area::AREA_ADMINHTML) . DIRECTORY_SEPARATOR;
|
||||
} else {
|
||||
$subdirectoryPattern .= '(?!' . ucfirst(Area::AREA_ADMINHTML) . ')';
|
||||
}
|
||||
|
||||
$actions = preg_grep('~' . $subdirectoryPattern . '~', $files);
|
||||
|
||||
$actionsPattern = '#' . $subdirectoryPattern . '(?<controller>\S+)/'
|
||||
. '(?<action_name>\w+)\.php$#';
|
||||
|
||||
$moduleActionsMapping = [];
|
||||
foreach ($actions as $action) {
|
||||
if (preg_match($actionsPattern, $action, $matches)) {
|
||||
$controllerName = strtolower(str_replace('/', '_', $matches['controller']));
|
||||
$actionName = strtolower($matches['action_name']);
|
||||
if (!isset($moduleActionsMapping[$controllerName][$actionName])) {
|
||||
$moduleActionsMapping[$controllerName][$actionName] = [];
|
||||
}
|
||||
$moduleActionsMapping[$controllerName][$actionName][] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
return $moduleActionsMapping;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
/**
|
||||
* Rule for searching dependencies in layout files
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency;
|
||||
|
||||
interface RuleInterface
|
||||
{
|
||||
/**
|
||||
* Types of dependencies between modules
|
||||
*/
|
||||
const TYPE_SOFT = 'soft';
|
||||
|
||||
const TYPE_HARD = 'hard';
|
||||
|
||||
/**
|
||||
* Gets alien dependencies information for current module by analyzing file's contents
|
||||
*
|
||||
* @param string $currentModule
|
||||
* @param string $fileType
|
||||
* @param string $file
|
||||
* @param string $contents
|
||||
* @return array
|
||||
*/
|
||||
public function getDependencyInfo($currentModule, $fileType, $file, &$contents);
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
/**
|
||||
* Rule for searching php file dependency
|
||||
*
|
||||
* Copyright © Magento, Inc. All rights reserved.
|
||||
* See COPYING.txt for license details.
|
||||
*/
|
||||
namespace Magento\TestFramework\Dependency\VirtualType;
|
||||
|
||||
use DOMDocument;
|
||||
use Magento\Framework\App\Utility\Files;
|
||||
|
||||
class VirtualTypeMapper
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $map = [];
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private static $mainScope = 'global';
|
||||
|
||||
/**
|
||||
* VirtualTypeMapper constructor.
|
||||
* @param array $map
|
||||
*/
|
||||
public function __construct(array $map = [])
|
||||
{
|
||||
$this->map = $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param string $scope
|
||||
* @return string|null
|
||||
*/
|
||||
public function getType($name, $scope = null)
|
||||
{
|
||||
if (empty($this->map)) {
|
||||
$this->loadMap();
|
||||
}
|
||||
|
||||
$scopes = [];
|
||||
if ($scope !== null && $scope !== self::$mainScope) {
|
||||
array_unshift($scopes, $scope);
|
||||
}
|
||||
$scopes[] = self::$mainScope;
|
||||
foreach ($scopes as $scp) {
|
||||
if (isset($this->map[$scp][$name])) {
|
||||
return $this->map[$scp][$name];
|
||||
}
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $file
|
||||
* @return string
|
||||
*/
|
||||
public function getScopeFromFile($file)
|
||||
{
|
||||
$basename = basename(pathinfo($file, PATHINFO_DIRNAME));
|
||||
return $basename === 'etc' ? 'global' : $basename;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function loadDiConfigs()
|
||||
{
|
||||
return Files::init()->getDiConfigs();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $diFiles
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function loadMap(array $diFiles = [])
|
||||
{
|
||||
if (empty($diFiles)) {
|
||||
$diFiles = $this->loadDiConfigs();
|
||||
}
|
||||
|
||||
foreach ($diFiles as $file) {
|
||||
$scope = $this->getScopeFromFile($file);
|
||||
$doc = new DOMDocument();
|
||||
$doc->loadXML(file_get_contents($file));
|
||||
$nodes = $doc->getElementsByTagName('virtualType');
|
||||
/** @var \DOMElement $node */
|
||||
foreach ($nodes as $node) {
|
||||
$name = $node->getAttribute('name');
|
||||
$type = $node->getAttribute('type');
|
||||
if (empty($type)) {
|
||||
continue;
|
||||
}
|
||||
$this->map[$scope][$name] = $type;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->map;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user