diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 88e79f495..daaeb45c7 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -5,7 +5,7 @@ name: Run automated tests on: pull_request: - branches: [ master, 4.2.0-develop ] + branches: [ master, 4.2.3-develop ] jobs: build-linux: diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d8e21220..067d0fcc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,74 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0). +## 4.2.3 + +## 4.2.2 + +### Added + +- Added custom search scope to exclude test files from search [#read-more](https://github.com/magento/magento2-phpstorm-plugin/wiki/4.2.2-Release) +- Added the ability to open all plugins in the Find Tool Window [#read-more](https://github.com/magento/magento2-phpstorm-plugin/wiki/4.2.2-Release) +- Added uiComponent registration syntax highlighting as JSON [#read-more](https://github.com/magento/magento2-phpstorm-plugin/wiki/4.2.2-Release) +- Added new Magento version support (2.4.4-beta4) for the UCT feature in [#922](https://github.com/magento/magento2-phpstorm-plugin/pull/922) + +### Changed + +- Eliminated com.google.gson.JsonParser#parse usage in [#928](https://github.com/magento/magento2-phpstorm-plugin/pull/928) +- Eliminated LineMarkerXmlTagDecorator#checkDelete usage in [#910](https://github.com/magento/magento2-phpstorm-plugin/pull/910) +- Eliminated LineMarkerXmlTagDecorator#checkAdd usage in [#909](https://github.com/magento/magento2-phpstorm-plugin/pull/909) +- Enhanced errors showing for the new Magento 2 UI Component Form dialog window in [#892](https://github.com/magento/magento2-phpstorm-plugin/pull/892) +- Enhanced errors showing for the new Magento 2 UI Component Grid dialog window in [#891](https://github.com/magento/magento2-phpstorm-plugin/pull/891) +- Enhanced errors showing for the new Magento 2 DB Schema XML dialog window in [#890](https://github.com/magento/magento2-phpstorm-plugin/pull/890) +- Enhanced errors showing for the new Magento 2 Message Queue dialog window in [#889](https://github.com/magento/magento2-phpstorm-plugin/pull/889) +- Enhanced errors showing for the new Magento 2 Data Model dialog window in [#888](https://github.com/magento/magento2-phpstorm-plugin/pull/888) +- Enhanced errors showing for the new Magento 2 Models dialog window in [#887](https://github.com/magento/magento2-phpstorm-plugin/pull/887) +- Enhanced errors showing for the new Magento 2 Email Template dialog window in [#886](https://github.com/magento/magento2-phpstorm-plugin/pull/886) +- Enhanced errors showing for the new Magento 2 CLI Command dialog window in [#885](https://github.com/magento/magento2-phpstorm-plugin/pull/885) +- Enhanced errors showing for the new Magento 2 GraphQl Resolver dialog window in [#884](https://github.com/magento/magento2-phpstorm-plugin/pull/884) +- Enhanced errors showing for the new Magento 2 View Model dialog window in [#883](https://github.com/magento/magento2-phpstorm-plugin/pull/883) +- Enhanced errors showing for the new Magento 2 Cron Group dialog window in [#882](https://github.com/magento/magento2-phpstorm-plugin/pull/882) +- Enhanced errors showing for the new Magento 2 Cron Job dialog window in [#881](https://github.com/magento/magento2-phpstorm-plugin/pull/881) +- Enhanced errors showing for the new Magento 2 Controller dialog window in [#880](https://github.com/magento/magento2-phpstorm-plugin/pull/880) +- Enhanced errors showing for the new Magento 2 Block dialog window in [#865](https://github.com/magento/magento2-phpstorm-plugin/pull/865) + +### Fixed + +- Fixed overriding layouts and templates allows to select an incompatible theme in [#930](https://github.com/magento/magento2-phpstorm-plugin/pull/930) +- Fixed observer action visibility in [#936](https://github.com/magento/magento2-phpstorm-plugin/pull/936) +- Fixed general exception while accessing phpIndex.getAnyByFQN(classFQN) in [#934](https://github.com/magento/magento2-phpstorm-plugin/pull/934) +- Fixed ClassCastException for the GraphQlResolverIndex.getGraphQLUsages in [#927](https://github.com/magento/magento2-phpstorm-plugin/pull/927) +- Fixed plugin inspection does not work correctly in [#902](https://github.com/magento/magento2-phpstorm-plugin/pull/902) +- Fixed module name declaration inspection flags valid code in [#898](https://github.com/magento/magento2-phpstorm-plugin/pull/898) +- Fixed ClassCastException: PsiPlainTextFileImpl cannot be cast to class XmlFile in WebApiTypeIndex in [#897](https://github.com/magento/magento2-phpstorm-plugin/pull/897) +- Fixed IndexNotReadyException while opening a context menu in [#896](https://github.com/magento/magento2-phpstorm-plugin/pull/896) +- Fixed IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern in [#894](https://github.com/magento/magento2-phpstorm-plugin/pull/894) +- Fixed Throwable: AWT events are not allowed inside write action (UI Form) in [#893](https://github.com/magento/magento2-phpstorm-plugin/pull/893) +- Fixed Slow operations are prohibited on EDT when calling update method on the CreateAPluginAction in [#862](https://github.com/magento/magento2-phpstorm-plugin/pull/862) +- Fixed Throwable: when an IOException is thrown during new plugin generation in [#860](https://github.com/magento/magento2-phpstorm-plugin/pull/860) +- Fixed IndexOutOfBoundsException in case when entered no fields during ui form generation in [#859](https://github.com/magento/magento2-phpstorm-plugin/pull/859) +- Fixed NullPointerException when opening new cron job dialog for an invalid Magento 2 module in [#856](https://github.com/magento/magento2-phpstorm-plugin/pull/856) +- Fixed NoSuchElementException when creating new controller in [#844](https://github.com/magento/magento2-phpstorm-plugin/pull/844) +- Fixed Message Queue Connection does not match Naming Conventions in [#854](https://github.com/magento/magento2-phpstorm-plugin/pull/854) +- Fixed StringIndexOutOfBoundsException during UCT inspection via action execution in [852](https://github.com/magento/magento2-phpstorm-plugin/pull/852) +- Fixed NullPointerException in the PluginDeclarationInspection.fetchModuleNamesWhereSamePluginNameUsed (calling toString on null) in [#849](https://github.com/magento/magento2-phpstorm-plugin/pull/849) + +## 4.2.1 + +### Fixed + +- Fixed ArrayIndexOutOfBoundsException when used Copy Path/Reference action on the requirejs-config.js file in [#808](https://github.com/magento/magento2-phpstorm-plugin/pull/808) +- Fixed dialog disposition issue in [#811](https://github.com/magento/magento2-phpstorm-plugin/pull/811) +- Fixed stack overflow error for line-marker providers in [#813](https://github.com/magento/magento2-phpstorm-plugin/pull/813) +- Fixed stub ids not found for key in index in [#814](https://github.com/magento/magento2-phpstorm-plugin/pull/814) +- Fixed failed to build require-js index in [815](https://github.com/magento/magento2-phpstorm-plugin/pull/815) +- Fixed empty psi elements in the plugin inspections in [#816](https://github.com/magento/magento2-phpstorm-plugin/pull/816) +- Fixed empty psi element in module xml inspection in [#817](https://github.com/magento/magento2-phpstorm-plugin/pull/817) +- Fixed NullPointerException for the firstSortOrder.compareTo in [#818](https://github.com/magento/magento2-phpstorm-plugin/pull/818) +- Fixed invalid column types provided exception during db_schema.xml file generation in [#819](https://github.com/magento/magento2-phpstorm-plugin/pull/819) +- Fixed method designed for fully qualified names only in [#830](https://github.com/magento/magento2-phpstorm-plugin/pull/830) +- Fixed NoClassDefFoundError for com.intellij.lang.jsgraphql.GraphQLIcons in [#850](https://github.com/magento/magento2-phpstorm-plugin/pull/850) + ## 4.2.0 ### Added diff --git a/README.md b/README.md index 89214bcf7..4ec852d74 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ 1. Check out this repository 1. Open a folder with the project in the IntelliJ Ultimate using the `open` action button. -1. Make sure that you on the latest develop branch (e.g `4.2.0-develop`) +1. Make sure that you on the latest develop branch (e.g `4.2.3-develop`) 1. Right-click on the `build.gradle` file, choose "Import Gradle project" (if this is not exist look for "Build module ''") (you need to have Gradle plugin installed) 1. Check if the right SDK version is used for the project. - Current Java version for the project is **java 11**, so you should additionally download **SDK 11** and choose it in the module settings: `Right click by the project root > Open Module Settings > Project Settings > Project > Project SDK` diff --git a/build.gradle b/build.gradle index 366739199..a759398ca 100644 --- a/build.gradle +++ b/build.gradle @@ -15,7 +15,7 @@ repositories { } group 'com.magento.idea' -version '4.2.0' +version '4.2.3' apply plugin: 'org.jetbrains.intellij' apply plugin: 'java' @@ -41,7 +41,7 @@ intellij { 'properties', 'CSS', 'JavaScriptLanguage', - 'com.intellij.lang.jsgraphql:3.0.0', + 'com.intellij.lang.jsgraphql:3.1.2', 'platform-images', 'copyright' ] @@ -69,7 +69,7 @@ sourceSets { publishPlugin { token = System.getenv("MAGENTO_PHPSTORM_intellijPublishToken") if (Boolean.valueOf(System.getenv("MAGENTO_PHPSTORM_isAlpha"))) { - channels 'alpha' + channels = ['alpha'] version = version + "-alpha-" + getDate() } } @@ -106,6 +106,7 @@ idea { dependencies { testImplementation 'junit:junit:4.13' + implementation 'org.json:json:20211205' } test { diff --git a/resources/META-INF/plugin.xml b/resources/META-INF/plugin.xml index c22b26d43..a97148de3 100644 --- a/resources/META-INF/plugin.xml +++ b/resources/META-INF/plugin.xml @@ -7,7 +7,7 @@ com.magento.idea.magento2plugin Magento PhpStorm - 4.2.0 + 4.2.3 Magento Inc. + + + + + diff --git a/resources/magento2/validation.properties b/resources/magento2/validation.properties index 8fec08b55..b868b58fb 100644 --- a/resources/magento2/validation.properties +++ b/resources/magento2/validation.properties @@ -1,6 +1,7 @@ validator.notEmpty=The {0} field must not be empty validator.box.notEmpty=The {0} field must contain a valid selection from the dropdown validator.package.validPath=Please specify a valid Magento 2 installation path +validator.properties.notEmpty=The properties must not be empty validator.alphaNumericCharacters=The {0} field must contain letters and numbers only validator.alphaNumericAndUnderscoreCharacters={0} must contain letters, numbers and underscores only validator.alphaAndPeriodCharacters=The {0} field must contain alphabets and periods only @@ -22,6 +23,7 @@ validator.command.isNotValid=The {0} field does not contain a valid Magento 2 CL validator.module.noSuchModule=No such module {0} validator.file.alreadyExists={0} already exists validator.file.cantBeCreated={0} can't be created +validator.file.cantBeCreatedWithException=The ''{0}'' cannot be created. Original message was: ''{1}'' validator.file.isNotWritable=%s file is binary or has no document associations validator.file.noDocumentAssociations={0} file is binary or has no document associations validator.class.alreadyDeclared={0} already declared in the target module @@ -38,3 +40,4 @@ validator.db.invalidTableNameLength=Table name must contain up to 64 characters validator.lowerSnakeCase=The {0} field must be of the lower snake case format validator.menuIdentifierInvalid=The menu identifier is invalid validator.someFieldsHaveErrors=Please, check the dialog. Some fields have errors +validator.dbSchema.invalidColumnType=Invalid ''{0}'' column type specified diff --git a/resources/uct/api/indexes.API_COVERAGE.idc b/resources/uct/api/indexes.API_COVERAGE.idc index c98fe32da..eb7c2eb21 100644 Binary files a/resources/uct/api/indexes.API_COVERAGE.idc and b/resources/uct/api/indexes.API_COVERAGE.idc differ diff --git a/resources/uct/deprecation/indexes.v2.4.4-beta4.DEPRECATION.idc b/resources/uct/deprecation/indexes.v2.4.4-beta4.DEPRECATION.idc new file mode 100644 index 000000000..9b81f6045 Binary files /dev/null and b/resources/uct/deprecation/indexes.v2.4.4-beta4.DEPRECATION.idc differ diff --git a/resources/uct/existence/indexes.EXISTENCE.idc b/resources/uct/existence/indexes.EXISTENCE.idc index b5d6f57fe..eadf97ebc 100644 Binary files a/resources/uct/existence/indexes.EXISTENCE.idc and b/resources/uct/existence/indexes.EXISTENCE.idc differ diff --git a/src/com/magento/idea/magento2plugin/actions/CopyMagentoPath.java b/src/com/magento/idea/magento2plugin/actions/CopyMagentoPath.java index ac79aebbe..1e1bc0be5 100644 --- a/src/com/magento/idea/magento2plugin/actions/CopyMagentoPath.java +++ b/src/com/magento/idea/magento2plugin/actions/CopyMagentoPath.java @@ -21,6 +21,7 @@ import org.jetbrains.annotations.Nullable; public class CopyMagentoPath extends CopyPathProvider { + public static final String PHTML_EXTENSION = "phtml"; public static final String JS_EXTENSION = "js"; public static final String CSS_EXTENSION = "css"; @@ -56,23 +57,23 @@ private boolean isNotValidFile(final VirtualFile virtualFile) { || virtualFile != null && !acceptedTypes.contains(virtualFile.getExtension()); } - @Nullable @Override - public String getPathToElement( - @NotNull final Project project, - @Nullable final VirtualFile virtualFile, - @Nullable final Editor editor + public @Nullable String getPathToElement( + final @NotNull Project project, + final @Nullable VirtualFile virtualFile, + final @Nullable Editor editor ) { if (virtualFile == null) { return null; } - final PsiFile file - = PsiManager.getInstance(project).findFile(virtualFile); + final PsiFile file = PsiManager.getInstance(project).findFile(virtualFile); + if (file == null) { return null; } final PsiDirectory directory = file.getContainingDirectory(); final String moduleName = GetModuleNameByDirectoryUtil.execute(directory, project); + if (moduleName == null) { return null; } @@ -89,8 +90,14 @@ public String getPathToElement( } else { return fullPath.toString(); } + int endIndex; - final int endIndex = getIndexOf(paths, fullPath, paths[++index]); + try { + endIndex = getIndexOf(paths, fullPath, paths[++index]); + } catch (ArrayIndexOutOfBoundsException exception) { + // endIndex could not be found. + return ""; + } final int offset = paths[index].length(); fullPath.replace(0, endIndex + offset, ""); @@ -98,6 +105,15 @@ public String getPathToElement( return moduleName + SEPARATOR + fullPath; } + /** + * Get index where web|template path starts in the fullPath. + * + * @param paths String[] + * @param fullPath StringBuilder + * @param path String + * + * @return int + */ private int getIndexOf(final String[] paths, final StringBuilder fullPath, final String path) { return fullPath.lastIndexOf(path) == -1 ? getIndexOf(paths, fullPath, paths[++index]) diff --git a/src/com/magento/idea/magento2plugin/actions/generation/CreateAPluginAction.java b/src/com/magento/idea/magento2plugin/actions/generation/CreateAPluginAction.java index 8c560d2b8..96b017534 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/CreateAPluginAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/CreateAPluginAction.java @@ -25,6 +25,7 @@ import org.jetbrains.annotations.NotNull; public class CreateAPluginAction extends DumbAwareAction { + public static final String ACTION_NAME = "Create a new Plugin for this method"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Plugin"; private final GetFirstClassOfFile getFirstClassOfFile; @@ -47,10 +48,12 @@ public void update(final AnActionEvent event) { targetClass = null;// NOPMD targetMethod = null;// NOPMD final Project project = event.getData(PlatformDataKeys.PROJECT); - if (Settings.isEnabled(project)) { + + if (project != null && Settings.isEnabled(project)) { final Pair pair = this.findPhpClass(event); final PsiFile psiFile = pair.getFirst(); final PhpClass phpClass = pair.getSecond(); + if (phpClass == null || !(psiFile instanceof PhpFile) || phpClass.isFinal() @@ -74,8 +77,13 @@ private void setStatus(final AnActionEvent event, final boolean status) { } @Override - public void actionPerformed(@NotNull final AnActionEvent event) { - CreateAPluginDialog.open(event.getProject(), this.targetMethod, this.targetClass); + public void actionPerformed(final @NotNull AnActionEvent event) { + final Project project = event.getProject(); + + if (project == null) { + return; + } + CreateAPluginDialog.open(project, this.targetMethod, this.targetClass); } @Override @@ -83,7 +91,7 @@ public boolean isDumbAware() { return false; } - private Pair findPhpClass(@NotNull final AnActionEvent event) { + private Pair findPhpClass(final @NotNull AnActionEvent event) { final PsiFile psiFile = event.getData(PlatformDataKeys.PSI_FILE); PhpClass phpClass = null; @@ -96,27 +104,31 @@ private Pair findPhpClass(@NotNull final AnActionEvent event) } private void fetchTargetMethod( - @NotNull final AnActionEvent event, + final @NotNull AnActionEvent event, final PsiFile psiFile, final PhpClass phpClass ) { final Caret caret = event.getData(PlatformDataKeys.CARET); + if (caret == null) { return; } final int offset = caret.getOffset(); final PsiElement element = psiFile.findElementAt(offset); + if (element == null) { return; } - if (element instanceof Method && element.getParent() - == phpClass && IsPluginAllowedForMethodUtil.check((Method) element)) { + + if (element instanceof Method && element.getParent().equals(phpClass) + && IsPluginAllowedForMethodUtil.check((Method) element)) { this.targetMethod = (Method) element; return; } final PsiElement parent = element.getParent(); - if (parent instanceof Method && parent.getParent() - == phpClass && IsPluginAllowedForMethodUtil.check((Method) parent)) { + + if (parent instanceof Method && parent.getParent().equals(phpClass) + && IsPluginAllowedForMethodUtil.check((Method) parent)) { this.targetMethod = (Method) parent; } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/CreateAnObserverAction.java b/src/com/magento/idea/magento2plugin/actions/generation/CreateAnObserverAction.java index 0253d897f..238f4dff7 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/CreateAnObserverAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/CreateAnObserverAction.java @@ -28,6 +28,7 @@ import org.jetbrains.annotations.NotNull; public class CreateAnObserverAction extends DumbAwareAction { + public static final String ACTION_NAME = "Create a new Observer for this event"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Observer"; public String targetEvent; @@ -40,19 +41,24 @@ public CreateAnObserverAction() { * Updates the state of action. */ @Override - public void update(final AnActionEvent event) { + public void update(final @NotNull AnActionEvent event) { final Project project = event.getData(PlatformDataKeys.PROJECT); + if (project == null) { + return; + } + if (!Settings.isEnabled(project)) { this.setStatus(event, false); return; } final PsiFile psiFile = event.getData(PlatformDataKeys.PSI_FILE); + if (!(psiFile instanceof PhpFile)) { this.setStatus(event, false); return; } - final PsiElement element = getElement(event); + if (element == null) { this.setStatus(event, false); return; @@ -67,21 +73,36 @@ public void update(final AnActionEvent event) { this.setStatus(event, false); } - private PsiElement getElement(@NotNull final AnActionEvent event) { + @Override + public void actionPerformed(final @NotNull AnActionEvent event) { + if (event.getProject() == null) { + return; + } + CreateAnObserverDialog.open(event.getProject(), this.targetEvent); + } + + @Override + public boolean isDumbAware() { + return false; + } + + private PsiElement getElement(final @NotNull AnActionEvent event) { final Caret caret = event.getData(PlatformDataKeys.CARET); + if (caret == null) { return null; } - final int offset = caret.getOffset(); final PsiFile psiFile = event.getData(PlatformDataKeys.PSI_FILE); - final PsiElement element = psiFile.findElementAt(offset); - if (element == null) { + + if (psiFile == null) { return null; } - return element; + final int offset = caret.getOffset(); + + return psiFile.findElementAt(offset); } - private boolean isObserverEventNameClicked(@NotNull final PsiElement element) { + private boolean isObserverEventNameClicked(final @NotNull PsiElement element) { return checkIsElementStringLiteral(element) && checkIsParametersList(element.getParent().getParent()) && checkIsMethodReference(element.getParent().getParent().getParent()) @@ -90,11 +111,11 @@ && checkIsEventDispatchMethod( ); } - private boolean checkIsParametersList(@NotNull final PsiElement element) { + private boolean checkIsParametersList(final @NotNull PsiElement element) { return element instanceof ParameterList; } - private boolean checkIsMethodReference(@NotNull final PsiElement element) { + private boolean checkIsMethodReference(final @NotNull PsiElement element) { return element instanceof MethodReference; } @@ -107,7 +128,7 @@ private boolean checkIsEventDispatchMethod(final MethodReference element) { if (!(method instanceof Method)) { return false; } - if (!((Method) method).getName().equals(Observer.DISPATCH_METHOD)) { + if (!Observer.DISPATCH_METHOD.equals(((Method) method).getName())) { return false; } final PsiElement phpClass = method.getParent(); @@ -115,32 +136,26 @@ private boolean checkIsEventDispatchMethod(final MethodReference element) { return false; } final String fqn = ((PhpClass) phpClass).getPresentableFQN(); - return fqn.equals(Observer.INTERFACE); + + return Observer.INTERFACE.equals(fqn) + || Observer.IMPLEMENTATION.equals(fqn) + || Observer.ENTITY_IMPL.equals(fqn) + || Observer.STAGING_IMPL.equals(fqn); } - private boolean checkIsElementStringLiteral(@NotNull final PsiElement element) { + private boolean checkIsElementStringLiteral(final @NotNull PsiElement element) { final ASTNode astNode = element.getNode(); if (astNode == null) { return false; } final IElementType elementType = astNode.getElementType(); - return elementType == PhpTokenTypes.STRING_LITERAL - || elementType == PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE; + return elementType.equals(PhpTokenTypes.STRING_LITERAL) + || elementType.equals(PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE); } private void setStatus(final AnActionEvent event, final boolean status) { event.getPresentation().setVisible(status); event.getPresentation().setEnabled(status); } - - @Override - public void actionPerformed(@NotNull final AnActionEvent event) { - CreateAnObserverDialog.open(event.getProject(), this.targetEvent); - } - - @Override - public boolean isDumbAware() { - return false; - } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewBlockAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewBlockAction.java index cefba0e7c..1fe6a3db4 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewBlockAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewBlockAction.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; public class NewBlockAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Block"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Block"; @@ -26,23 +27,24 @@ public NewBlockAction() { } @Override - public void actionPerformed(@NotNull final AnActionEvent event) { + public void actionPerformed(final @NotNull AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewBlockDialog.open(project, directory); } @@ -51,4 +53,3 @@ public boolean isDumbAware() { return false; } } - diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewCLICommandAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewCLICommandAction.java index 41bf7c68a..e352d29e4 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewCLICommandAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewCLICommandAction.java @@ -17,33 +17,33 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.NewCLICommandDialog; import org.jetbrains.annotations.NotNull; -@SuppressWarnings({"PMD.FieldNamingConventions", "PMD.OnlyOneReturn"}) public class NewCLICommandAction extends AnAction { - public static String ACTION_NAME = "Magento 2 CLI Command"; - public static String ACTION_DESCRIPTION = "Create a new Magento 2 CLI Command"; + + public static final String ACTION_NAME = "Magento 2 CLI Command"; + public static final String ACTION_DESCRIPTION = "Create a new Magento 2 CLI Command"; public NewCLICommandAction() { super(ACTION_NAME, ACTION_DESCRIPTION, MagentoIcons.MODULE); } @Override - public void actionPerformed(@NotNull final AnActionEvent event) { + public void actionPerformed(final @NotNull AnActionEvent event) { final DataContext context = event.getDataContext(); final IdeView view = LangDataKeys.IDE_VIEW.getData(context); + if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(context); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewCLICommandDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewControllerAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewControllerAction.java index 277636830..9460114bd 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewControllerAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewControllerAction.java @@ -16,8 +16,8 @@ import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.actions.generation.dialog.NewControllerDialog; -@SuppressWarnings({"PMD.OnlyOneReturn", "PMD.FieldNamingConventions"}) public class NewControllerAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Controller"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Controller"; @@ -36,13 +36,13 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewCronGroupAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewCronGroupAction.java index c9908eac8..175d7ef66 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewCronGroupAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewCronGroupAction.java @@ -15,8 +15,8 @@ import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.actions.generation.dialog.NewCronGroupDialog; -@SuppressWarnings({"PMD.OnlyOneReturn"}) public class NewCronGroupAction extends com.intellij.openapi.actionSystem.AnAction { + public static final String ACTION_NAME = "Magento 2 Cron Group"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Cron Group"; @@ -35,18 +35,16 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); if (directory == null) { return; } - NewCronGroupDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewCronjobAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewCronjobAction.java index 538df7a1e..948174758 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewCronjobAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewCronjobAction.java @@ -17,10 +17,10 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.NewCronjobDialog; import org.jetbrains.annotations.NotNull; -@SuppressWarnings({"PMD.FieldNamingConventions", "PMD.OnlyOneReturn"}) public class NewCronjobAction extends AnAction { - public static String ACTION_NAME = "Magento 2 Cron Job"; - public static String ACTION_DESCRIPTION = "Create a new Magento 2 Cron Job"; + + public static final String ACTION_NAME = "Magento 2 Cron Job"; + public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Cron Job"; public NewCronjobAction() { super(ACTION_NAME, ACTION_DESCRIPTION, MagentoIcons.MODULE); @@ -34,17 +34,16 @@ public void actionPerformed(final @NotNull AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewCronjobDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewDataModelAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewDataModelAction.java index e15ff1551..cd3393b26 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewDataModelAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewDataModelAction.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; public class NewDataModelAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Data Model"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Data Model"; @@ -29,24 +30,23 @@ public NewDataModelAction() { } @Override - public void actionPerformed(@NotNull final AnActionEvent event) { + public void actionPerformed(final @NotNull AnActionEvent event) { final DataContext dataContext = event.getDataContext(); - final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewDataModelDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewDbSchemaAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewDbSchemaAction.java index f2a76930f..ee2997166 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewDbSchemaAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewDbSchemaAction.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; public class NewDbSchemaAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Declarative Schema XML"; public static final String ACTION_DESCRIPTION = "Create a new declarative schema XML"; @@ -32,16 +33,17 @@ public NewDbSchemaAction() { public void actionPerformed(final @NotNull AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewEmailTemplateAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewEmailTemplateAction.java index 78a99904b..ca7007625 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewEmailTemplateAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewEmailTemplateAction.java @@ -16,8 +16,8 @@ import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.actions.generation.dialog.NewEmailTemplateDialog; -@SuppressWarnings({"PMD.OnlyOneReturn", "PMD.FieldNamingConventions"}) public class NewEmailTemplateAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Email Template"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 email template"; @@ -36,17 +36,16 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewEmailTemplateDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewGraphQlResolverAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewGraphQlResolverAction.java index 4792ae19d..347e6b5c2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewGraphQlResolverAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewGraphQlResolverAction.java @@ -2,10 +2,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.actions.generation; import com.intellij.ide.IdeView; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import com.magento.idea.magento2plugin.MagentoIcons; @@ -13,31 +18,32 @@ import org.jetbrains.annotations.NotNull; public class NewGraphQlResolverAction extends AnAction { - public static String ACTION_NAME = "Magento 2 GraphQL Resolver"; - public static String ACTION_DESCRIPTION = "Create a new Magento 2 GraphQL Resolver"; - NewGraphQlResolverAction() { + public static final String ACTION_NAME = "Magento 2 GraphQL Resolver"; + public static final String ACTION_DESCRIPTION = "Create a new Magento 2 GraphQL Resolver"; + + public NewGraphQlResolverAction() { super(ACTION_NAME, ACTION_DESCRIPTION, MagentoIcons.MODULE); } @Override - public void actionPerformed(@NotNull AnActionEvent e) { - DataContext dataContext = e.getDataContext(); - IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + public void actionPerformed(final @NotNull AnActionEvent event) { + final DataContext dataContext = event.getDataContext(); + final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } + final Project project = CommonDataKeys.PROJECT.getData(dataContext); - Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { return; } + final PsiDirectory directory = view.getOrChooseDirectory(); - PsiDirectory directory = view.getOrChooseDirectory(); if (directory == null) { return; } - NewGraphQlResolverDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewMessageQueueAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewMessageQueueAction.java index d562f076a..f66d9f1d0 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewMessageQueueAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewMessageQueueAction.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; public class NewMessageQueueAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Message Queue"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 Message Queue"; @@ -29,24 +30,23 @@ public NewMessageQueueAction() { } @Override - public void actionPerformed(@NotNull final AnActionEvent event) { + public void actionPerformed(final @NotNull AnActionEvent event) { final DataContext dataContext = event.getDataContext(); - final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewMessageQueueDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewModelsAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewModelsAction.java index e9034f882..1567d41eb 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewModelsAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewModelsAction.java @@ -17,6 +17,7 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.NewModelsDialog; public class NewModelsAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 Models"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 models"; @@ -35,17 +36,16 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewModelsDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentFormAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentFormAction.java index 5c099949d..502013c88 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentFormAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentFormAction.java @@ -17,6 +17,7 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.NewUiComponentFormDialog; public class NewUiComponentFormAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 UI Component Form"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 UI Component Form"; @@ -35,17 +36,16 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); + if (directory == null) { return; } - NewUiComponentFormDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentGridAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentGridAction.java index f507f9051..e2f4a0f5f 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentGridAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewUiComponentGridAction.java @@ -16,8 +16,8 @@ import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.actions.generation.dialog.NewUiComponentGridDialog; -@SuppressWarnings({"PMD.OnlyOneReturn"}) public class NewUiComponentGridAction extends AnAction { + public static final String ACTION_NAME = "Magento 2 UI Component Grid"; public static final String ACTION_DESCRIPTION = "Create a new Magento 2 UI Component Grid"; @@ -41,18 +41,16 @@ public void actionPerformed(final AnActionEvent event) { if (view == null) { return; } - final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) { return; } - final PsiDirectory directory = view.getOrChooseDirectory(); if (directory == null) { return; } - NewUiComponentGridDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/NewViewModelAction.java b/src/com/magento/idea/magento2plugin/actions/generation/NewViewModelAction.java index 7d4f8c075..53e72f68d 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/NewViewModelAction.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/NewViewModelAction.java @@ -2,10 +2,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.actions.generation; import com.intellij.ide.IdeView; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import com.magento.idea.magento2plugin.MagentoIcons; @@ -13,31 +18,32 @@ import org.jetbrains.annotations.NotNull; public class NewViewModelAction extends AnAction { - public static String ACTION_NAME = "Magento 2 View Model"; - public static String ACTION_DESCRIPTION = "Create a new Magento 2 View Model"; - NewViewModelAction() { + public static final String ACTION_NAME = "Magento 2 View Model"; + public static final String ACTION_DESCRIPTION = "Create a new Magento 2 View Model"; + + public NewViewModelAction() { super(ACTION_NAME, ACTION_DESCRIPTION, MagentoIcons.MODULE); } @Override - public void actionPerformed(@NotNull AnActionEvent e) { - DataContext dataContext = e.getDataContext(); - IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + public void actionPerformed(final @NotNull AnActionEvent event) { + final DataContext dataContext = event.getDataContext(); + final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); + if (view == null) { return; } + final Project project = CommonDataKeys.PROJECT.getData(dataContext); - Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { return; } + final PsiDirectory directory = view.getOrChooseDirectory(); - PsiDirectory directory = view.getOrChooseDirectory(); if (directory == null) { return; } - NewViewModelDialog.open(project, directory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/AbstractDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/AbstractDialog.java index c793f6fcc..4ea9b7d4b 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/AbstractDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/AbstractDialog.java @@ -59,8 +59,18 @@ protected void centerDialog(final AbstractDialog dialog) { dialog.setLocation(coordinateX, coordinateY); } + /** + * Default on cancel action. + */ protected void onCancel() { - this.setVisible(false); + this.exit(); + } + + /** + * Right way to hide dialog window. + */ + protected void exit() { + dispose(); } /** diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAPluginDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAPluginDialog.java index 0bec74d19..c2257e1ae 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAPluginDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAPluginDialog.java @@ -157,30 +157,28 @@ private void fillTargetAreaOptions() { } protected void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + new PluginClassGenerator(new PluginFileData( + getPluginDirectory(), + getPluginClassName(), + getPluginType(), + getPluginModule(), + targetClass, + targetMethod, + getPluginClassFqn(), + getNamespace() + ), project).generate(CreateAPluginAction.ACTION_NAME, true); + + new PluginDiXmlGenerator(new PluginDiXmlData( + getPluginArea(), + getPluginModule(), + targetClass, + getPluginSortOrder(), + getPluginName(), + getPluginClassFqn() + ), project).generate(CreateAPluginAction.ACTION_NAME); } - new PluginClassGenerator(new PluginFileData( - getPluginDirectory(), - getPluginClassName(), - getPluginType(), - getPluginModule(), - targetClass, - targetMethod, - getPluginClassFqn(), - getNamespace() - ), project).generate(CreateAPluginAction.ACTION_NAME, true); - - new PluginDiXmlGenerator(new PluginDiXmlData( - getPluginArea(), - getPluginModule(), - targetClass, - getPluginSortOrder(), - getPluginName(), - getPluginClassFqn() - ), project).generate(CreateAPluginAction.ACTION_NAME); - - this.setVisible(false); + exit(); } public String getPluginName() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAnObserverDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAnObserverDialog.java index 920c7e233..223ecee01 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAnObserverDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/CreateAnObserverDialog.java @@ -150,27 +150,25 @@ private void fillTargetAreaOptions() { * Perform code generation using input data. */ private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + new ObserverClassGenerator(new ObserverFileData( + getObserverDirectory(), + getObserverClassName(), + getObserverModule(), + targetEvent, + getObserverClassFqn(), + getNamespace() + ), project).generate(CreateAnObserverAction.ACTION_NAME, true); + + new ObserverEventsXmlGenerator(new ObserverEventsXmlData( + getObserverArea(), + getObserverModule(), + targetEvent, + getObserverName(), + getObserverClassFqn() + ), project).generate(CreateAPluginAction.ACTION_NAME); } - new ObserverClassGenerator(new ObserverFileData( - getObserverDirectory(), - getObserverClassName(), - getObserverModule(), - targetEvent, - getObserverClassFqn(), - getNamespace() - ), project).generate(CreateAnObserverAction.ACTION_NAME, true); - - new ObserverEventsXmlGenerator(new ObserverEventsXmlData( - getObserverArea(), - getObserverModule(), - targetEvent, - getObserverName(), - getObserverClassFqn() - ), project).generate(CreateAPluginAction.ACTION_NAME); - - this.setVisible(false); + exit(); } public String getObserverClassName() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/InjectAViewModelDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/InjectAViewModelDialog.java index 8252be35c..19bd8b1ec 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/InjectAViewModelDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/InjectAViewModelDialog.java @@ -138,6 +138,7 @@ protected void updateArgumentText() { protected void onOK() { if (!validateFormFields()) { + exit(); return; } final String moduleName = GetModuleNameByDirectoryUtil.execute( @@ -168,6 +169,7 @@ protected void onOK() { JOptionPane.ERROR_MESSAGE ); + exit(); return; } @@ -176,9 +178,9 @@ protected void onOK() { this.getViewModelArgumentName(), XsiTypes.object.toString(), namespaceBuilder.getClassFqn() - ).generate(targetBlockTag); + ).generate(targetBlockTag); - this.setVisible(false); + exit(); } public String getViewModelClassName() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.form index 9689cc6a0..c460ac6fa 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.form @@ -53,7 +53,7 @@ - + @@ -85,7 +85,7 @@ - + @@ -96,7 +96,7 @@ - + @@ -106,6 +106,22 @@ + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.java index e215d7364..44342993a 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewBlockDialog.java @@ -7,7 +7,6 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; import com.magento.idea.magento2plugin.actions.generation.NewBlockAction; import com.magento.idea.magento2plugin.actions.generation.data.BlockFileData; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.annotation.FieldValidation; @@ -26,6 +25,7 @@ import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; @@ -33,6 +33,7 @@ import javax.swing.KeyStroke; public class NewBlockDialog extends AbstractDialog { + private final PsiDirectory baseDir; private final String moduleName; private JPanel contentPanel; @@ -44,18 +45,18 @@ public class NewBlockDialog extends AbstractDialog { private static final String NAME = "name"; private static final String DIRECTORY = "directory"; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, NAME}) - @FieldValidation(rule = RuleRegistry.PHP_CLASS, - message = {PhpClassRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.PHP_CLASS, message = {PhpClassRule.MESSAGE, NAME}) private JTextField blockName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, DIRECTORY}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, DIRECTORY}) @FieldValidation(rule = RuleRegistry.PHP_DIRECTORY, message = {PhpDirectoryRule.MESSAGE, DIRECTORY}) private JTextField blockParentDir; + private JLabel blockNameErrorMessage;//NOPMD + private JLabel blockParentDirErrorMessage;//NOPMD + /** * Constructor. * @@ -111,15 +112,14 @@ public static void open(final Project project, final PsiDirectory directory) { } protected void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFile(); + exit(); } - generateFile(); - this.setVisible(false); } - private PsiFile generateFile() { - return new ModuleBlockClassGenerator(new BlockFileData( + private void generateFile() { + new ModuleBlockClassGenerator(new BlockFileData( getBlockDirectory(), getBlockName(), getModuleName(), @@ -141,6 +141,7 @@ public String getBlockDirectory() { private void suggestBlockDirectory() { final String moduleIdentifierPath = getModuleIdentifierPath(); + if (moduleIdentifierPath == null) { blockParentDir.setText(BlockPhp.DEFAULT_DIR); return; @@ -148,6 +149,7 @@ private void suggestBlockDirectory() { final String path = baseDir.getVirtualFile().getPath(); final String[] pathParts = path.split(moduleIdentifierPath); final int minimumPathParts = 2; + if (pathParts.length != minimumPathParts) { blockParentDir.setText(BlockPhp.DEFAULT_DIR); return; @@ -162,14 +164,17 @@ private void suggestBlockDirectory() { private String getModuleIdentifierPath() { final String[]parts = moduleName.split(Package.vendorModuleNameSeparator); + if (parts[0] == null || parts[1] == null || parts.length > 2) { return null; } + return parts[0] + File.separator + parts[1]; } private String getNamespace() { final String[]parts = moduleName.split(Package.vendorModuleNameSeparator); + if (parts[0] == null || parts[1] == null || parts.length > 2) { return null; } @@ -177,12 +182,7 @@ private String getNamespace() { File.separator, Package.fqnSeparator ); - return parts[0] + Package.fqnSeparator + parts[1] + Package.fqnSeparator + directoryPart; - } - @Override - public void onCancel() { - // add your code here if necessary - dispose(); + return parts[0] + Package.fqnSeparator + parts[1] + Package.fqnSeparator + directoryPart; } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.form index cc459ee59..43b98f5b5 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.form @@ -16,7 +16,7 @@ - + @@ -36,7 +36,7 @@ - + @@ -46,7 +46,7 @@ - + @@ -65,7 +65,7 @@ - + @@ -74,7 +74,7 @@ - + @@ -83,7 +83,7 @@ - + @@ -93,7 +93,7 @@ - + @@ -128,7 +128,7 @@ - + @@ -137,6 +137,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.java index def6d7eaa..26a085f41 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCLICommandDialog.java @@ -30,22 +30,26 @@ import java.util.Locale; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; +import org.jetbrains.annotations.NotNull; @SuppressWarnings({"PMD.MissingSerialVersionUID", "PMD.ExcessiveImports"}) public class NewCLICommandDialog extends AbstractDialog { - private JPanel contentPane; - private JButton buttonCancel; - private JButton buttonOK; + private static final String CLASS_NAME = "class name"; private static final String PARENT_DIRECTORY = "parent directory"; private static final String COMMAND_NAME = "command name"; private static final String COMMAND_DESCRIPTION = "description"; + private JPanel contentPane; + private JButton buttonCancel; + private JButton buttonOK; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, CLASS_NAME}) @FieldValidation(rule = RuleRegistry.PHP_CLASS, @@ -68,6 +72,11 @@ public class NewCLICommandDialog extends AbstractDialog { message = {NotEmptyRule.MESSAGE, COMMAND_DESCRIPTION}) private JTextArea cliCommandDescriptionField; + private JLabel cliCommandClassNameFieldErrorMessage;//NOPMD + private JLabel cliCommandParentDirectoryFieldErrorMessage;//NOPMD + private JLabel cliCommandNameFieldErrorMessage;//NOPMD + private JLabel cliCommandDescriptionFieldErrorMessage;//NOPMD + private final CommonBundle commonBundle; private final Project project; private final String moduleName; @@ -79,7 +88,10 @@ public class NewCLICommandDialog extends AbstractDialog { * @param project Project * @param directory PsiDirectory */ - public NewCLICommandDialog(final Project project, final PsiDirectory directory) { + public NewCLICommandDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; this.moduleName = GetModuleNameByDirectoryUtil.execute(directory, project); @@ -179,11 +191,10 @@ public String getCLICommandClassFqn() { } private void onOK() { - if (!validateFormFields() || !isPHPClassValid()) { - return; + if (validateFormFields() && isPHPClassValid()) { + this.generate(); + exit(); } - this.generate(); - this.setVisible(false); } private Boolean isPHPClassValid() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.form index 59cbf84c0..5abf1a5be 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.form @@ -3,7 +3,7 @@ - + @@ -51,7 +51,7 @@ - + @@ -61,7 +61,7 @@ - + @@ -69,7 +69,7 @@ - + @@ -79,7 +79,7 @@ - + @@ -87,7 +87,7 @@ - + @@ -111,6 +111,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -118,6 +142,7 @@ + @@ -145,6 +170,7 @@ + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.java index 7e1e3627e..402cedb96 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewControllerDialog.java @@ -33,6 +33,7 @@ import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; @@ -43,6 +44,7 @@ "PMD.ExcessiveImports" }) public class NewControllerDialog extends AbstractDialog { + private final String moduleName; private final Project project; private JPanel contentPane; @@ -50,7 +52,6 @@ public class NewControllerDialog extends AbstractDialog { private JButton buttonCancel; private FilteredComboBox controllerAreaSelect; private FilteredComboBox httpMethodSelect; - private JTextField controllerParentDir; private JCheckBox inheritClass; private JPanel adminPanel; private JTextField acl; @@ -64,12 +65,16 @@ public class NewControllerDialog extends AbstractDialog { message = {PhpDirectoryRule.MESSAGE, CONTROLLER_NAME}) private JTextField controllerName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, ACTION_NAME}) - @FieldValidation(rule = RuleRegistry.PHP_CLASS, - message = {PhpClassRule.MESSAGE, ACTION_NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, ACTION_NAME}) + @FieldValidation(rule = RuleRegistry.PHP_CLASS, message = {PhpClassRule.MESSAGE, ACTION_NAME}) private JTextField actionName; + private JTextField controllerParentDir; + + private JLabel actionNameErrorMessage;//NOPMD + private JLabel controllerNameErrorMessage;//NOPMD + private JLabel controllerParentDirErrorMessage;//NOPMD + /** * Open new dialog for adding new controller. * @@ -194,12 +199,10 @@ public static void open(final Project project, final PsiDirectory directory) { } private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFile(); + exit(); } - - generateFile(); - this.setVisible(false); } /** @@ -251,12 +254,13 @@ private String getNamespace() { ); return String.format( - "%s%s%s%s%s%s", + "%s%s%s%s%s%s%s", parts[0], Package.fqnSeparator, parts[1], Package.fqnSeparator, directoryPart, + Package.fqnSeparator, controllerPart ); } @@ -265,11 +269,6 @@ private Boolean getIsInheritClass() { return inheritClass.isSelected(); } - @Override - protected void onCancel() { - dispose(); - } - private List getAreaList() { return new ArrayList<>( Arrays.asList( diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.form index 629d61e1e..030b9841e 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.form @@ -49,7 +49,7 @@ - + @@ -59,7 +59,7 @@ - + @@ -67,7 +67,7 @@ - + @@ -75,7 +75,7 @@ - + @@ -83,7 +83,7 @@ - + @@ -91,7 +91,7 @@ - + @@ -99,7 +99,7 @@ - + @@ -107,43 +107,43 @@ - + - + - + - + - + - + - + @@ -151,7 +151,7 @@ - + @@ -159,7 +159,7 @@ - + @@ -168,7 +168,7 @@ - + @@ -177,7 +177,7 @@ - + @@ -186,7 +186,7 @@ - + @@ -195,7 +195,7 @@ - + @@ -204,7 +204,7 @@ - + @@ -213,7 +213,7 @@ - + @@ -221,7 +221,7 @@ - + @@ -247,7 +247,7 @@ - + @@ -255,7 +255,7 @@ - + @@ -263,7 +263,7 @@ - + @@ -271,7 +271,7 @@ - + @@ -279,7 +279,7 @@ - + @@ -287,7 +287,7 @@ - + @@ -295,7 +295,7 @@ - + @@ -304,7 +304,7 @@ - + @@ -312,7 +312,7 @@ - + @@ -320,7 +320,7 @@ - + @@ -331,9 +331,17 @@ - + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.java index 64f76277c..28ddbd615 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronGroupDialog.java @@ -25,6 +25,7 @@ import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; @@ -37,6 +38,7 @@ "PMD.ExcessiveImports," }) public class NewCronGroupDialog extends AbstractDialog { + private final String moduleName; private final Project project; private JPanel contentPanel; @@ -44,10 +46,8 @@ public class NewCronGroupDialog extends AbstractDialog { private JButton buttonCancel; private static final String NAME = "name"; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, NAME}) - @FieldValidation(rule = RuleRegistry.IDENTIFIER, - message = {IdentifierRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, NAME}) private JTextField cronGroupName; private JSpinner scheduleGenerateEvery; @@ -65,6 +65,8 @@ public class NewCronGroupDialog extends AbstractDialog { private FilteredComboBox useSeparateProcess; private JCheckBox addUseSeparateProcess; + private JLabel cronGroupNameErrorMessage;//NOPMD + /** * New CRON group dialogue constructor. * @@ -140,17 +142,10 @@ public static void open(final Project project, final PsiDirectory directory) { } private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFile(); + exit(); } - - generateFile(); - this.setVisible(false); - } - - @Override - protected void onCancel() { - dispose(); } private void generateFile() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.form index bfb797c3d..1da079a05 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.form @@ -3,9 +3,11 @@ - + - + + + @@ -49,7 +51,7 @@ - + @@ -78,7 +80,7 @@ - + @@ -87,7 +89,7 @@ - + @@ -95,12 +97,12 @@ - + - + @@ -109,16 +111,16 @@ - + - + - + @@ -162,12 +164,20 @@ + + + + + + + + - + @@ -194,7 +204,7 @@ - + @@ -202,7 +212,7 @@ - + @@ -210,7 +220,7 @@ - + @@ -218,7 +228,7 @@ - + @@ -226,7 +236,7 @@ - + @@ -235,6 +245,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.java index 4682f9f8e..a8f71b0f1 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewCronjobDialog.java @@ -35,11 +35,13 @@ import java.util.List; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.KeyStroke; +import org.jetbrains.annotations.NotNull; @SuppressWarnings({ "PMD.UncommentedEmptyMethodBody", @@ -54,6 +56,11 @@ "PMD.ExcessiveImports", }) public class NewCronjobDialog extends AbstractDialog { + + private final Project project; + private final String moduleName; + private final CamelCaseToSnakeCase camelCaseToSnakeCase; + private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; @@ -64,6 +71,7 @@ public class NewCronjobDialog extends AbstractDialog { private JRadioButton atMidnightRadioButton; private JPanel fixedSchedulePanel; private JPanel configurableSchedulePanel; + private static final String CLASS_NAME = "class name"; private static final String DIRECTORY = "directory"; private static final String CRON_NAME = "name"; @@ -107,9 +115,12 @@ public class NewCronjobDialog extends AbstractDialog { message = {NotEmptyRule.MESSAGE, CRON_GROUP}) private FilteredComboBox cronGroupComboBox; - private Project project; - private String moduleName; - private CamelCaseToSnakeCase camelCaseToSnakeCase; + private JLabel cronjobClassNameFieldErrorMessage;//NOPMD + private JLabel cronjobDirectoryFieldErrorMessage;//NOPMD + private JLabel cronjobNameFieldErrorMessage;//NOPMD + private JLabel cronGroupComboBoxErrorMessage;//NOPMD + private JLabel cronjobScheduleFieldErrorMessage;//NOPMD + private JLabel configPathFieldErrorMessage;//NOPMD /** * Open a new cronjob generation dialog form. @@ -117,7 +128,7 @@ public class NewCronjobDialog extends AbstractDialog { * @param project Project * @param directory Directory */ - public NewCronjobDialog(final Project project, final PsiDirectory directory) { + public NewCronjobDialog(final @NotNull Project project, final @NotNull PsiDirectory directory) { super(); this.project = project; this.moduleName = GetModuleNameByDirectoryUtil.execute(directory, project); @@ -246,11 +257,6 @@ public String getCronjobScheduleConfigPath() { return this.configPathField.getText().trim(); } - @Override - protected void onCancel() { - dispose(); - } - private void createUIComponents() { final List cronGroups = CronGroupIndex.getInstance(project).getGroups(); @@ -263,15 +269,19 @@ private void createUIComponents() { * @return String */ private String suggestCronjobName(final String cronjobClassname) { + if (moduleName == null) { + return ""; + } + if (cronjobClassname == null || cronjobClassname.isEmpty()) { - return this.moduleName.toLowerCase(new java.util.Locale("en","EN")); + return moduleName.toLowerCase(new java.util.Locale("en","EN")); } final String cronjobClassnameToSnakeCase = this.camelCaseToSnakeCase.convert( cronjobClassname ); - return this.moduleName.toLowerCase(new java.util.Locale("en","EN")) + return moduleName.toLowerCase(new java.util.Locale("en","EN")) + "_" + cronjobClassnameToSnakeCase; } @@ -283,7 +293,6 @@ private void onOK() { if (!validateFormFields()) { return; } - final NamespaceBuilder namespaceBuilder = new NamespaceBuilder( this.getCronjobModule(), this.getCronjobClassName(), @@ -298,7 +307,7 @@ private void onOK() { // todo: catch validation exceptions this.generate(cronjobClassData, crontabXmlData); - this.setVisible(false); + exit(); } /** diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.form index 9d58d7228..b9b2cb84b 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.form @@ -10,7 +10,7 @@ - + @@ -36,6 +36,14 @@ + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.java index 64baf0743..1c907d7a9 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDataModelDialog.java @@ -40,6 +40,7 @@ import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTable; @@ -47,24 +48,25 @@ import javax.swing.KeyStroke; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; +import org.jetbrains.annotations.NotNull; @SuppressWarnings({ "PMD.ExcessiveImports" }) public class NewDataModelDialog extends AbstractDialog { - private final Project project; - private final String moduleName; - private final ValidatorBundle validatorBundle; - private final CommonBundle commonBundle; - private final List properties; - private static final String MODEL_NAME = "Model Name"; private static final String PROPERTY_NAME = "Name"; private static final String PROPERTY_TYPE = "Type"; private static final String PROPERTY_ACTION = "Action"; private static final String PROPERTY_DELETE = "Delete"; + private final Project project; + private final String moduleName; + private final ValidatorBundle validatorBundle; + private final CommonBundle commonBundle; + private final List properties; + private JPanel contentPanel; private JButton buttonOK; private JButton buttonCancel; @@ -72,16 +74,19 @@ public class NewDataModelDialog extends AbstractDialog { private JButton addProperty; private JCheckBox createInterface; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, MODEL_NAME}) - @FieldValidation(rule = RuleRegistry.PHP_CLASS, - message = {PhpClassRule.MESSAGE, MODEL_NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, MODEL_NAME}) + @FieldValidation(rule = RuleRegistry.PHP_CLASS, message = {PhpClassRule.MESSAGE, MODEL_NAME}) private JTextField modelName; + private JLabel modelNameErrorMessage;//NOPMD + /** * Constructor. */ - public NewDataModelDialog(final Project project, final PsiDirectory directory) { + public NewDataModelDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; @@ -122,7 +127,10 @@ public void windowClosing(final WindowEvent event) { /** * Opens the dialog window. */ - public static void open(final Project project, final PsiDirectory directory) { + public static void open( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { final NewDataModelDialog dialog = new NewDataModelDialog(project, directory); dialog.pack(); dialog.centerDialog(dialog); @@ -145,7 +153,7 @@ private void onOK() { generateDataModelInterfaceFile(); generatePreferenceForInterface(); } - this.setVisible(false); + exit(); } } @@ -157,6 +165,17 @@ protected boolean validateFormFields() { valid = true; final String errorTitle = commonBundle.message("common.error"); final int column = 0; + + if (propertyTable.getRowCount() == 0) { + valid = false; + JOptionPane.showMessageDialog( + null, + validatorBundle.message("validator.properties.notEmpty"), + errorTitle, + JOptionPane.ERROR_MESSAGE + ); + } + for (int row = 0; row < propertyTable.getRowCount(); row++) { final String propertyName = ((String) propertyTable.getValueAt(row, column)).trim(); if (propertyName.isEmpty()) { @@ -190,11 +209,6 @@ protected boolean validateFormFields() { return valid; } - @Override - public void onCancel() { - dispose(); - } - /** * Generate DTO interface file. */ diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.form index 7c48e7d9b..78ac30fdd 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.form @@ -56,7 +56,7 @@ - + @@ -92,7 +92,7 @@ - + @@ -101,7 +101,7 @@ - + @@ -110,7 +110,7 @@ - + @@ -118,7 +118,7 @@ - + @@ -128,6 +128,14 @@ + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.java index 818280fea..020b17443 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewDbSchemaDialog.java @@ -7,6 +7,7 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiFile; import com.magento.idea.magento2plugin.actions.generation.NewDbSchemaAction; import com.magento.idea.magento2plugin.actions.generation.data.DbSchemaXmlData; import com.magento.idea.magento2plugin.actions.generation.data.ui.ComboBoxItemData; @@ -45,6 +46,7 @@ @SuppressWarnings({"PMD.TooManyFields", "PMD.ExcessiveImports"}) public class NewDbSchemaDialog extends AbstractDialog { + private static final String TABLE_NAME = "Table Name"; private final Project project; @@ -84,6 +86,7 @@ public class NewDbSchemaDialog extends AbstractDialog { private JLabel tableResourceLabel;//NOPMD private JLabel tableCommentLabel;//NOPMD private JLabel tableColumnsLabel;//NOPMD + private JLabel tableNameErrorMessage;//NOPMD /** * Constructor. @@ -135,21 +138,22 @@ private void onOK() { columnsTable.getCellEditor().stopCellEditing(); } - if (!validateFormFields()) { - return; - } - - final DbSchemaXmlData dbSchemaXmlData = new DbSchemaXmlData( - getTableName(), - getTableResource(), - getTableEngine(), - getTableComment(), - getColumns() - ); - generateDbSchemaXmlFile(dbSchemaXmlData); - generateWhitelistJsonFile(dbSchemaXmlData); + if (validateFormFields()) { + final DbSchemaXmlData dbSchemaXmlData = new DbSchemaXmlData( + getTableName(), + getTableResource(), + getTableEngine(), + getTableComment(), + getColumns() + ); + final PsiFile dbSchemaXmlFile = generateDbSchemaXmlFile(dbSchemaXmlData); - this.setVisible(false); + if (dbSchemaXmlFile == null) { + return; + } + generateWhitelistJsonFile(dbSchemaXmlData); + exit(); + } } /** @@ -173,8 +177,8 @@ public static void open( * * @param dbSchemaXmlData DbSchemaXmlData */ - private void generateDbSchemaXmlFile(final @NotNull DbSchemaXmlData dbSchemaXmlData) { - new DbSchemaXmlGenerator( + private PsiFile generateDbSchemaXmlFile(final @NotNull DbSchemaXmlData dbSchemaXmlData) { + return new DbSchemaXmlGenerator( dbSchemaXmlData, project, moduleName diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.form index 1c074587b..411ec0e9d 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.form @@ -3,9 +3,11 @@ - + - + + + @@ -49,7 +51,7 @@ - + @@ -75,7 +77,7 @@ - + @@ -83,7 +85,7 @@ - + @@ -91,7 +93,7 @@ - + @@ -99,7 +101,7 @@ - + @@ -107,7 +109,7 @@ - + @@ -115,7 +117,7 @@ - + @@ -123,7 +125,7 @@ - + @@ -134,7 +136,7 @@ - + @@ -145,7 +147,7 @@ - + @@ -153,12 +155,36 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.java index 9d902e458..461f3588f 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEmailTemplateDialog.java @@ -21,8 +21,6 @@ import com.magento.idea.magento2plugin.magento.packages.Areas; import com.magento.idea.magento2plugin.ui.FilteredComboBox; import com.magento.idea.magento2plugin.util.magento.GetModuleNameByDirectoryUtil; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; @@ -31,37 +29,48 @@ import java.util.List; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; public class NewEmailTemplateDialog extends AbstractDialog { - private final String moduleName; - private final Project project; - private final NewEmailTemplateDialogValidator validator; + private static final String EMAIL_TEMPLATE_ID = "id"; private static final String LABEL = "label"; private static final String FILENAME = "file name"; + + private final String moduleName; + private final Project project; + private final NewEmailTemplateDialogValidator validator; private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, EMAIL_TEMPLATE_ID}) @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, EMAIL_TEMPLATE_ID}) private JTextField identifier; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, LABEL}) private JTextField label; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, FILENAME}) @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, FILENAME}) private JTextField fileName; + private FilteredComboBox area; private FilteredComboBox templateType; private JTextField subject; + private JLabel identifierErrorMessage;//NOPMD + private JLabel labelErrorMessage;//NOPMD + private JLabel fileNameErrorMessage;//NOPMD + /** * New email template dialog. * @@ -83,6 +92,8 @@ public NewEmailTemplateDialog(final Project project, final PsiDirectory director // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { + + @Override public void windowClosing(final WindowEvent windowEvent) { onCancel(); } @@ -90,11 +101,7 @@ public void windowClosing(final WindowEvent windowEvent) { // call onCancel() on ESCAPE contentPane.registerKeyboardAction( - new ActionListener() { - public void actionPerformed(final ActionEvent actionEvent) { - onCancel(); - } - }, + actionEvent -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); @@ -206,12 +213,12 @@ private String getModuleName() { private void onOK() { final boolean emailTemplateCanBeDeclared = !this.validator.validate(this); + if (!validateFormFields() || emailTemplateCanBeDeclared) { return; } - generateFile(); - this.setVisible(false); + exit(); } private void generateFile() { @@ -228,11 +235,6 @@ private void generateFile() { xmlGenerator.generate(NewEmailTemplateAction.ACTION_NAME, true); } - protected void onCancel() { - // add your code here if necessary - dispose(); - } - @SuppressWarnings({"PMD.UnusedPrivateMethod"}) private void createUIComponents() { this.area = new FilteredComboBox(getAreaList()); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEntityDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEntityDialog.java index 5437b96b7..1eca33353 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEntityDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewEntityDialog.java @@ -441,7 +441,7 @@ private void releaseDialogAfterGeneration() { buttonOK.setEnabled(true); if (onOkActionFired.isFinished()) { - this.setVisible(false); + exit(); } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.form index f16356523..7ad64638b 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.form @@ -7,12 +7,12 @@ - + - + @@ -44,7 +44,7 @@ - + @@ -55,7 +55,7 @@ - + @@ -65,6 +65,22 @@ + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.java index d5a37c77a..5990542f3 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewGraphQlResolverDialog.java @@ -7,7 +7,6 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; import com.magento.idea.magento2plugin.actions.generation.NewGraphQlResolverAction; import com.magento.idea.magento2plugin.actions.generation.data.GraphQlResolverFileData; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.annotation.FieldValidation; @@ -26,11 +25,14 @@ import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; +import org.jetbrains.annotations.NotNull; public class NewGraphQlResolverDialog extends AbstractDialog { + private final PsiDirectory baseDir; private final String moduleName; private JPanel contentPanel; @@ -52,13 +54,19 @@ public class NewGraphQlResolverDialog extends AbstractDialog { message = {PhpDirectoryRule.MESSAGE, PARENT_DIRECTORY}) private JTextField graphQlResolverParentDir; + private JLabel graphQlResolverClassNameErrorMessage;//NOPMD + private JLabel graphQlResolverParentDirErrorMessage;//NOPMD + /** * Constructor. * * @param project Project * @param directory PsiDirectory */ - public NewGraphQlResolverDialog(final Project project, final PsiDirectory directory) { + public NewGraphQlResolverDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; @@ -109,15 +117,14 @@ public static void open(final Project project, final PsiDirectory directory) { } protected void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFile(); + exit(); } - generateFile(); - this.setVisible(false); } - private PsiFile generateFile() { - return new ModuleGraphQlResolverClassGenerator(new GraphQlResolverFileData( + private void generateFile() { + new ModuleGraphQlResolverClassGenerator(new GraphQlResolverFileData( getGraphQlResolverDirectory(), getGraphQlResolverClassName(), getModuleName(), @@ -183,10 +190,4 @@ private String getNamespace() { private String getGraphQlResolverClassFqn() { return getNamespace().concat(Package.fqnSeparator).concat(getGraphQlResolverClassName()); } - - @Override - public void onCancel() { - // add your code here if necessary - dispose(); - } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewInterfaceForServiceDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewInterfaceForServiceDialog.java index 6c6851cfe..7f4f45ee3 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewInterfaceForServiceDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewInterfaceForServiceDialog.java @@ -170,17 +170,15 @@ private void fillPredefinedValuesAndDisableInputs() { * Fire generation process if all fields are valid. */ private void onOK() { - if (!validateFormFields()) { - return; - } - final WebApiInterfaceData data = getDialogDataObject(); + if (validateFormFields()) { + final WebApiInterfaceData data = getDialogDataObject(); - new WebApiInterfaceGenerator( - data, - project - ).generate(NewWebApiInterfaceAction.ACTION_NAME, true); - - this.setVisible(false); + new WebApiInterfaceGenerator( + data, + project + ).generate(NewWebApiInterfaceAction.ACTION_NAME, true); + } + exit(); } /** diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.form index ab56c7f34..13e9efda6 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.form @@ -7,11 +7,12 @@ + - + @@ -21,7 +22,7 @@ - + @@ -32,7 +33,7 @@ - + @@ -44,7 +45,7 @@ - + @@ -53,7 +54,7 @@ - + @@ -63,7 +64,7 @@ - + @@ -71,7 +72,7 @@ - + @@ -103,7 +104,7 @@ - + @@ -113,7 +114,7 @@ - + @@ -121,7 +122,7 @@ - + @@ -129,7 +130,7 @@ - + @@ -139,7 +140,7 @@ - + @@ -147,7 +148,7 @@ - + @@ -155,7 +156,7 @@ - + @@ -163,12 +164,76 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -212,7 +277,7 @@ - + @@ -222,7 +287,7 @@ - + @@ -232,7 +297,7 @@ - + @@ -240,7 +305,7 @@ - + @@ -253,7 +318,7 @@ - + @@ -270,7 +335,7 @@ - + @@ -280,7 +345,7 @@ - + @@ -288,7 +353,7 @@ - + @@ -312,6 +377,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.java index 96d2e52b6..816079a41 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewMessageQueueDialog.java @@ -19,6 +19,7 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.AlphaWithDashRule; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.AlphaWithPeriodRule; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.AlphanumericWithUnderscoreRule; +import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.DirectoryRule; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.Lowercase; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.NotEmptyRule; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.NumericRule; @@ -52,36 +53,37 @@ "PMD.ExcessiveImports", }) public class NewMessageQueueDialog extends AbstractDialog { + private static final String TOPIC_NAME = "Topic Name"; private static final String HANDLER_NAME = "Handler Name"; - private static final String HANDLER_TYPE = "Handler Type"; + private static final String HANDLER_TYPE = "Handler Class"; + private static final String HANDLER_DIR = "Handler Directory"; private static final String CONSUMER_NAME = "Consumer Name"; private static final String QUEUE_NAME = "Queue Name"; - private static final String CONSUMER_TYPE = "Consumer Type"; + private static final String CONSUMER_TYPE = "Consumer Class"; + private static final String CONSUMER_DIR = "Consumer Directory"; private static final String MAX_MESSAGES = "Maximum Messages"; private static final String EXCHANGE_NAME = "Exchange Name"; private static final String BINDING_ID = "Binding ID"; private static final String BINDING_TOPIC = "Binding Topic"; private JComboBox connectionName; + private final Project project; + private final String moduleName; /* TODO: Improve validation */ - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, TOPIC_NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, TOPIC_NAME}) @FieldValidation(rule = RuleRegistry.ALPHA_WITH_PERIOD, message = {AlphaWithPeriodRule.MESSAGE, TOPIC_NAME}) - @FieldValidation(rule = RuleRegistry.LOWERCASE, - message = {Lowercase.MESSAGE, TOPIC_NAME}) + @FieldValidation(rule = RuleRegistry.LOWERCASE, message = {Lowercase.MESSAGE, TOPIC_NAME}) private JTextField topicName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, HANDLER_NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, HANDLER_NAME}) @FieldValidation(rule = RuleRegistry.ALPHA_WITH_PERIOD, message = {AlphanumericWithUnderscoreRule.MESSAGE, HANDLER_NAME}) private JTextField handlerName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, HANDLER_TYPE}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, HANDLER_TYPE}) @FieldValidation(rule = RuleRegistry.PHP_CLASS, message = {PhpClassFqnRule.MESSAGE, HANDLER_TYPE}) private JTextField handlerClass; @@ -90,16 +92,13 @@ public class NewMessageQueueDialog extends AbstractDialog { message = {NotEmptyRule.MESSAGE, CONSUMER_NAME}) @FieldValidation(rule = RuleRegistry.ALPHA_WITH_PERIOD, message = {AlphaWithPeriodRule.MESSAGE, CONSUMER_NAME}) - @FieldValidation(rule = RuleRegistry.LOWERCASE, - message = {Lowercase.MESSAGE, CONSUMER_NAME}) + @FieldValidation(rule = RuleRegistry.LOWERCASE, message = {Lowercase.MESSAGE, CONSUMER_NAME}) private JTextField consumerName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, QUEUE_NAME}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, QUEUE_NAME}) @FieldValidation(rule = RuleRegistry.ALPHA_WITH_PERIOD, message = {AlphaWithPeriodRule.MESSAGE, QUEUE_NAME}) - @FieldValidation(rule = RuleRegistry.LOWERCASE, - message = {Lowercase.MESSAGE, QUEUE_NAME}) + @FieldValidation(rule = RuleRegistry.LOWERCASE, message = {Lowercase.MESSAGE, QUEUE_NAME}) private JTextField queueName; @FieldValidation(rule = RuleRegistry.NOT_EMPTY, @@ -108,10 +107,8 @@ public class NewMessageQueueDialog extends AbstractDialog { message = {PhpClassFqnRule.MESSAGE, CONSUMER_TYPE}) private JTextField consumerClass; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, MAX_MESSAGES}) - @FieldValidation(rule = RuleRegistry.NUMERIC, - message = {NumericRule.MESSAGE, MAX_MESSAGES}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, MAX_MESSAGES}) + @FieldValidation(rule = RuleRegistry.NUMERIC, message = {NumericRule.MESSAGE, MAX_MESSAGES}) private JTextField maxMessages; @FieldValidation(rule = RuleRegistry.NOT_EMPTY, @@ -120,8 +117,7 @@ public class NewMessageQueueDialog extends AbstractDialog { message = {AlphaWithDashRule.MESSAGE, EXCHANGE_NAME}) private JTextField exchangeName; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, - message = {NotEmptyRule.MESSAGE, BINDING_ID}) + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, BINDING_ID}) @FieldValidation(rule = RuleRegistry.ALPHANUMERIC_WITH_UNDERSCORE, message = {AlphaWithDashRule.MESSAGE, BINDING_ID}) private JTextField bindingId; @@ -132,7 +128,12 @@ public class NewMessageQueueDialog extends AbstractDialog { message = {AlphanumericWithUnderscoreRule.MESSAGE, BINDING_TOPIC}) private JTextField bindingTopic; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, CONSUMER_DIR}) + @FieldValidation(rule = RuleRegistry.DIRECTORY, message = {DirectoryRule.MESSAGE, CONSUMER_DIR}) private JTextField consumerDirectory; + + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, HANDLER_DIR}) + @FieldValidation(rule = RuleRegistry.DIRECTORY, message = {DirectoryRule.MESSAGE, HANDLER_DIR}) private JTextField handlerDirectory; private JPanel contentPanel; @@ -146,13 +147,29 @@ public class NewMessageQueueDialog extends AbstractDialog { private JLabel consumerNameLabel;//NOPMD private JLabel handlerDirectoryLabel;//NOPMD - private final Project project; - private final String moduleName; + private JLabel topicNameErrorMessage;//NOPMD + private JLabel handlerNameErrorMessage;//NOPMD + private JLabel handlerClassErrorMessage;//NOPMD + private JLabel consumerNameErrorMessage;//NOPMD + private JLabel queueNameErrorMessage;//NOPMD + private JLabel consumerClassErrorMessage;//NOPMD + private JLabel maxMessagesErrorMessage;//NOPMD + private JLabel exchangeNameErrorMessage;//NOPMD + private JLabel bindingIdErrorMessage;//NOPMD + private JLabel bindingTopicErrorMessage;//NOPMD + private JLabel consumerDirectoryErrorMessage;//NOPMD + private JLabel handlerDirectoryErrorMessage;//NOPMD /** * Constructor. + * + * @param project Project + * @param directory PsiDirectory */ - public NewMessageQueueDialog(final Project project, final PsiDirectory directory) { + public NewMessageQueueDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; @@ -224,19 +241,20 @@ private void toggleConsumer() { /** * Opens the dialog window. + * + * @param project Project + * @param directory PsiDirectory */ - public static void open(final Project project, final PsiDirectory directory) { + public static void open( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { final NewMessageQueueDialog dialog = new NewMessageQueueDialog(project, directory); dialog.pack(); dialog.centerDialog(dialog); dialog.setVisible(true); } - @Override - public void onCancel() { - dispose(); - } - private void onOK() { if (validateFormFields()) { generateCommunication(); @@ -244,10 +262,11 @@ private void onOK() { generateTopology(); generatePublisher(); generateHandlerClass(); + if (getConnectionName().equals(MessageQueueConnections.DB.getType())) { generateConsumerClass(); } - this.setVisible(false); + exit(); } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.form index ec6e68d88..da7a3a909 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.form @@ -3,10 +3,10 @@ - + - + @@ -51,7 +51,7 @@ - + @@ -77,7 +77,7 @@ - + @@ -85,7 +85,7 @@ - + @@ -93,7 +93,7 @@ - + @@ -101,7 +101,7 @@ - + @@ -109,7 +109,7 @@ - + @@ -119,7 +119,7 @@ - + @@ -127,7 +127,7 @@ - + @@ -137,7 +137,7 @@ - + @@ -145,7 +145,7 @@ - + @@ -155,12 +155,60 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.java index 9c91b9389..ca47d35b7 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModelsDialog.java @@ -35,6 +35,7 @@ @SuppressWarnings("PMD.TooManyFields") public class NewModelsDialog extends AbstractDialog { + private final String moduleName; private final Project project; private JPanel contentPane; @@ -91,6 +92,12 @@ public class NewModelsDialog extends AbstractDialog { private JLabel entityIdColumnLabel;//NOPMD private JLabel collectionDirectoryLabel;//NOPMD private JLabel collectionNameLabel;//NOPMD + private JLabel modelNameErrorMessage;//NOPMD + private JLabel resourceModelNameErrorMessage;//NOPMD + private JLabel dbTableNameErrorMessage;//NOPMD + private JLabel entityIdColumnErrorMessage;//NOPMD + private JLabel collectionDirectoryErrorMessage;//NOPMD + private JLabel collectionNameErrorMessage;//NOPMD /** * Open new dialog for adding new controller. @@ -160,24 +167,16 @@ public static void open( dialog.setVisible(true); } - @Override - protected void onCancel() { - dispose(); - } - /** * Process generation. */ private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateModelFile(); + generateResourceModelFile(); + generateCollectionFile(); + exit(); } - - generateModelFile(); - generateResourceModelFile(); - generateCollectionFile(); - - this.setVisible(false); } /** diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModuleDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModuleDialog.java index 0e2a18f9e..5ed7cfd66 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModuleDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewModuleDialog.java @@ -172,11 +172,10 @@ private void detectPackageName(final @NotNull PsiDirectory initialBaseDir) { } protected void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFiles(); } - generateFiles(); - this.setVisible(false); + exit(); } private void generateFiles() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.form index a5599e727..7add87217 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.form @@ -6,7 +6,7 @@ - + @@ -160,15 +160,15 @@ - - + + - + - + @@ -188,7 +188,7 @@ - + @@ -196,7 +196,7 @@ - + @@ -215,15 +215,31 @@ + + + + + + + + + + + + + + + + - - + + - + - + @@ -252,7 +268,7 @@ - + @@ -262,21 +278,37 @@ - + + + + + + + + + + + + + + + + + - - + + - + - + @@ -310,7 +342,7 @@ - + @@ -318,7 +350,7 @@ - + @@ -326,6 +358,22 @@ + + + + + + + + + + + + + + + + @@ -338,17 +386,17 @@ - - + + - + - + - + @@ -356,7 +404,7 @@ - + @@ -375,7 +423,7 @@ - + @@ -385,7 +433,7 @@ - + @@ -417,17 +465,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - + + + @@ -447,7 +521,7 @@ - + @@ -455,7 +529,7 @@ - + @@ -463,7 +537,7 @@ - + @@ -471,10 +545,34 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.java index 23e8b62e2..727ff0937 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentFormDialog.java @@ -71,6 +71,7 @@ import javax.swing.KeyStroke; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; +import org.jetbrains.annotations.NotNull; @SuppressWarnings({ "PMD.TooManyFields", @@ -80,6 +81,25 @@ "PMD.GodClass" }) public class NewUiComponentFormDialog extends AbstractDialog { + + private static final String VIEW_ACTION_NAME = "View Action Name"; + private static final String SUBMIT_ACTION_NAME = "Submit Action Name"; + private static final String DATA_PROVIDER_CLASS_NAME = "Data Provider Class Name"; + private static final String DATA_PROVIDER_DIRECTORY = "Data Provider Directory"; + + private static final String CLASS_COLUMN = "Class"; + private static final String DIRECTORY_COLUMN = "Directory"; + private static final String TYPE_COLUMN = "Type"; + private static final String LABEL_COLUMN = "Label"; + private static final String SORT_ORDER_COLUMN = "Sort Order"; + private static final String ACTION_COLUMN = "Action"; + private static final String DELETE_COLUMN = "Delete"; + private static final String NAME_COLUMN = "Name"; + private static final String FIELDSET_COLUMN = "Fieldset"; + private static final String FORM_ELEMENT_TYPE_COLUMN = "Form Element Type"; + private static final String DATA_TYPE_COLUMN = "Data Type"; + private static final String SOURCE_COLUMN = "Source"; + private final FormButtonsValidator formButtonsValidator; private final FormFieldsetsValidator formFieldsetsValidator; private final FormFieldsValidator formFieldsValidator; @@ -90,11 +110,6 @@ public class NewUiComponentFormDialog extends AbstractDialog { private JButton buttonCancel; private FilteredComboBox formAreaSelect; - private static final String VIEW_ACTION_NAME = "View Action Name"; - private static final String SUBMIT_ACTION_NAME = "Submit Action Name"; - private static final String DATA_PROVIDER_CLASS_NAME = "Data Provider Class Name"; - private static final String DATA_PROVIDER_DIRECTORY = "Data Provider Directory"; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, "Name"}) @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, "Name"}) private JTextField formName; @@ -180,19 +195,18 @@ public class NewUiComponentFormDialog extends AbstractDialog { private JLabel dataProviderLabel;//NOPMD private JLabel dataProviderClassNameLabel;//NOPMD private JLabel dataProviderDirectoryLabel;//NOPMD - - private static final String CLASS_COLUMN = "Class"; - private static final String DIRECTORY_COLUMN = "Directory"; - private static final String TYPE_COLUMN = "Type"; - private static final String LABEL_COLUMN = "Label"; - private static final String SORT_ORDER_COLUMN = "Sort Order"; - private static final String ACTION_COLUMN = "Action"; - private static final String DELETE_COLUMN = "Delete"; - private static final String NAME_COLUMN = "Name"; - private static final String FIELDSET_COLUMN = "Fieldset"; - private static final String FORM_ELEMENT_TYPE_COLUMN = "Form Element Type"; - private static final String DATA_TYPE_COLUMN = "Data Type"; - private static final String SOURCE_COLUMN = "Source"; + private JLabel formNameErrorMessage;//NOPMD + private JLabel formLabelErrorMessage;//NOPMD + private JLabel routeErrorMessage;//NOPMD + private JLabel viewControllerNameErrorMessage;//NOPMD + private JLabel viewActionNameErrorMessage;//NOPMD + private JLabel submitControllerNameErrorMessage;//NOPMD + private JLabel submitActionNameErrorMessage;//NOPMD + private JLabel dataProviderClassNameErrorMessage;//NOPMD + private JLabel dataProviderDirectoryErrorMessage;//NOPMD + private JLabel aclErrorMessage;//NOPMD + private JLabel parentAclErrorMessage;//NOPMD + private JLabel aclTitleErrorMessage;//NOPMD /** * Open new dialog for adding new controller. @@ -200,7 +214,10 @@ public class NewUiComponentFormDialog extends AbstractDialog { * @param project Project * @param directory PsiDirectory */ - public NewUiComponentFormDialog(final Project project, final PsiDirectory directory) { + public NewUiComponentFormDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; formButtonsValidator = new FormButtonsValidator(this); @@ -396,7 +413,10 @@ public String getArea() { * @param project Project * @param directory PsiDirectory */ - public static void open(final Project project, final PsiDirectory directory) { + public static void open( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { final NewUiComponentFormDialog dialog = new NewUiComponentFormDialog(project, directory); dialog.pack(); dialog.centerDialog(dialog); @@ -416,18 +436,16 @@ private void onOK() { fields.getCellEditor().stopCellEditing(); } - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateRoutesXmlFile(); + generateViewControllerFile(); + generateSubmitControllerFile(); + generateDataProviderFile(); + generateLayoutFile(); + generateFormFile(); + generateAclXmlFile(); + exit(); } - - generateRoutesXmlFile(); - generateViewControllerFile(); - generateSubmitControllerFile(); - generateDataProviderFile(); - generateLayoutFile(); - generateFormFile(); - generateAclXmlFile(); - this.setVisible(false); } /** @@ -538,11 +556,6 @@ private void generateAclXmlFile() { ), getModuleName(), project).generate(NewUiComponentFormAction.ACTION_NAME, false); } - @Override - protected void onCancel() { - dispose(); - } - private List getAreaList() { return new ArrayList<>( Arrays.asList( diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.form index 1030cda99..25d59d5c8 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.form @@ -3,7 +3,7 @@ - + @@ -65,7 +65,7 @@ - + @@ -75,7 +75,7 @@ - + @@ -85,7 +85,7 @@ - + @@ -93,7 +93,7 @@ - + @@ -104,7 +104,7 @@ - + @@ -135,9 +135,25 @@ + + + + + + + + + + + + + + + + - + @@ -155,7 +171,7 @@ - + @@ -163,7 +179,7 @@ - + @@ -171,7 +187,7 @@ - + @@ -179,7 +195,7 @@ - + @@ -187,7 +203,7 @@ - + @@ -195,7 +211,7 @@ - + @@ -216,9 +232,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -266,7 +314,7 @@ - + @@ -274,7 +322,7 @@ - + @@ -291,13 +339,13 @@ - + - + @@ -305,7 +353,7 @@ - + @@ -314,15 +362,31 @@ - + + + + + + + + + + + + + + + + + - + @@ -340,7 +404,7 @@ - + @@ -348,7 +412,7 @@ - + @@ -364,7 +428,7 @@ - + @@ -372,7 +436,7 @@ - + @@ -387,9 +451,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -415,7 +503,7 @@ - + @@ -423,13 +511,13 @@ - + - + @@ -437,7 +525,7 @@ - + @@ -452,6 +540,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.java index d5ec946b7..a46409b28 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewUiComponentGridDialog.java @@ -79,6 +79,7 @@ "PMD.GodClass" }) public class NewUiComponentGridDialog extends AbstractDialog { + private static final String ACTION_NAME = "Action Name"; private static final String DATA_PROVIDER_CLASS_NAME = "Data Provider Class Name"; private static final String DATA_PROVIDER_DIRECTORY = "Data Provider Directory"; @@ -91,25 +92,24 @@ public class NewUiComponentGridDialog extends AbstractDialog { private JButton buttonOK; private JButton buttonCancel; - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) - @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, NAME}) - private JTextField uiComponentName; - - @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) - @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, NAME}) - private JTextField idField; - private JCheckBox addToolBar; private JCheckBox addBookmarksCheckBox; private JCheckBox addColumnsControlCheckBox; private JCheckBox addFullTextSearchCheckBox; private JCheckBox addListingFiltersCheckBox; private JCheckBox addListingPagingCheckBox; - private FilteredComboBox collection; private FilteredComboBox dataProviderType; private FilteredComboBox areaSelect; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, NAME}) + private JTextField uiComponentName; + + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, NAME}) + @FieldValidation(rule = RuleRegistry.IDENTIFIER, message = {IdentifierRule.MESSAGE, NAME}) + private JTextField idField; + @FieldValidation(rule = RuleRegistry.NOT_EMPTY, message = {NotEmptyRule.MESSAGE, DATA_PROVIDER_CLASS_NAME}) @FieldValidation(rule = RuleRegistry.PHP_CLASS, @@ -168,6 +168,8 @@ public class NewUiComponentGridDialog extends AbstractDialog { message = {NotEmptyRule.MESSAGE, "Parent Menu"}) private FilteredComboBox parentMenu; + private JTextField tableName; + private JLabel aclLabel; private JLabel routeLabel;//NOPMD private JLabel controllerLabel;//NOPMD @@ -186,7 +188,20 @@ public class NewUiComponentGridDialog extends AbstractDialog { private JLabel collectionLabel;//NOPMD private JLabel dataProviderParentDirectoryLabel; private JLabel tableNameLabel; - private JTextField tableName; + private JLabel uiComponentNameErrorMessage;//NOPMD + private JLabel idFieldErrorMessage;//NOPMD + private JLabel providerClassNameErrorMessage;//NOPMD + private JLabel dataProviderParentDirectoryErrorMessage;//NOPMD + private JLabel aclErrorMessage;//NOPMD + private JLabel parentAclErrorMessage;//NOPMD + private JLabel aclTitleErrorMessage;//NOPMD + private JLabel routeErrorMessage;//NOPMD + private JLabel controllerNameErrorMessage;//NOPMD + private JLabel actionNameErrorMessage;//NOPMD + private JLabel sortOrderErrorMessage;//NOPMD + private JLabel menuIdentifierErrorMessage;//NOPMD + private JLabel menuTitleErrorMessage;//NOPMD + private JLabel parentMenuErrorMessage;//NOPMD /** * New UI component grid dialog constructor. @@ -194,7 +209,10 @@ public class NewUiComponentGridDialog extends AbstractDialog { * @param project Project * @param directory PsiDirectory */ - public NewUiComponentGridDialog(final Project project, final PsiDirectory directory) { + public NewUiComponentGridDialog( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { super(); this.project = project; this.moduleName = GetModuleNameByDirectoryUtil.execute(directory, project); @@ -244,7 +262,10 @@ public void windowClosing(final WindowEvent event) { * @param project Project * @param directory PsiDirectory */ - public static void open(final Project project, final PsiDirectory directory) { + public static void open( + final @NotNull Project project, + final @NotNull PsiDirectory directory + ) { final NewUiComponentGridDialog dialog = new NewUiComponentGridDialog(project, directory); dialog.pack(); dialog.centerDialog(dialog); @@ -303,19 +324,17 @@ protected void onCancel() { } private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateViewControllerFile(); + generateLayoutFile(); + generateMenuFile(); + generateAclXmlFile(); + generateRoutesXmlFile(); + generateDataProviderClass(); + generateDataProviderDeclaration(); + generateUiComponentFile(); + exit(); } - - generateViewControllerFile(); - generateLayoutFile(); - generateMenuFile(); - generateAclXmlFile(); - generateRoutesXmlFile(); - generateDataProviderClass(); - generateDataProviderDeclaration(); - generateUiComponentFile(); - this.setVisible(false); } private void setDefaultValues() { @@ -354,7 +373,7 @@ private void generateUiComponentFile() { * Generate data provider class. */ private void generateDataProviderClass() { - if (getDataProviderType().equals(UiComponentDataProviderFile.CUSTOM_TYPE)) { + if (UiComponentDataProviderFile.CUSTOM_TYPE.equals(getDataProviderType())) { final UiComponentDataProviderGenerator dataProviderGenerator; dataProviderGenerator = new UiComponentDataProviderGenerator( getGridDataProviderData(), @@ -369,7 +388,7 @@ private void generateDataProviderClass() { * Generate data provider declaration. */ private void generateDataProviderDeclaration() { - if (getDataProviderType().equals(UiComponentDataProviderFile.COLLECTION_TYPE)) { + if (UiComponentDataProviderFile.COLLECTION_TYPE.equals(getDataProviderType())) { final DataProviderDeclarationGenerator dataProviderGenerator; dataProviderGenerator = new DataProviderDeclarationGenerator( new DataProviderDeclarationData( @@ -465,8 +484,8 @@ private void onAreaChange() { } private void onDataProviderTypeChange() { - final boolean visible = getDataProviderType().equals( - UiComponentDataProviderFile.COLLECTION_TYPE + final boolean visible = UiComponentDataProviderFile.COLLECTION_TYPE.equals( + getDataProviderType() ); collection.setVisible(visible); @@ -556,7 +575,7 @@ private String getDataProviderNamespace() { } private String getDataProviderClassFqn() { - if (!getDataProviderType().equals(UiComponentDataProviderFile.CUSTOM_TYPE)) { + if (!UiComponentDataProviderFile.CUSTOM_TYPE.equals(getDataProviderType())) { return UiComponentDataProviderFile.DEFAULT_DATA_PROVIDER; } return String.format( diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.form b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.form index 88c8a9b83..fa05e157a 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.form +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.form @@ -7,12 +7,12 @@ - + - + @@ -22,7 +22,7 @@ - + @@ -44,7 +44,7 @@ - + @@ -55,7 +55,7 @@ - + @@ -65,6 +65,22 @@ + + + + + + + + + + + + + + + + diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.java index 8403927c1..283004fa2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewViewModelDialog.java @@ -7,7 +7,6 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; import com.magento.idea.magento2plugin.actions.generation.NewViewModelAction; import com.magento.idea.magento2plugin.actions.generation.data.ViewModelFileData; import com.magento.idea.magento2plugin.actions.generation.dialog.validator.annotation.FieldValidation; @@ -28,13 +27,17 @@ import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JComponent; +import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; public class NewViewModelDialog extends AbstractDialog { + private static final String VIEW_MODEL_NAME = "View Model Name"; private static final String VIEW_MODEL_DIR = "View Model Directory"; + + private final Project project; private final PsiDirectory baseDir; private final String moduleName; @@ -58,7 +61,8 @@ public class NewViewModelDialog extends AbstractDialog { message = {DirectoryRule.MESSAGE, VIEW_MODEL_DIR}) private JTextField viewModelParentDir; - private final Project project; + private JLabel viewModelNameErrorMessage;//NOPMD + private JLabel viewModelParentDirErrorMessage;//NOPMD /** * Constructor. @@ -117,15 +121,14 @@ public static void open(final Project project, final PsiDirectory directory) { } protected void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + generateFile(); + exit(); } - generateFile(); - this.setVisible(false); } - private PsiFile generateFile() { - return new ModuleViewModelClassGenerator(new ViewModelFileData( + private void generateFile() { + new ModuleViewModelClassGenerator(new ViewModelFileData( getViewModelDirectory(), getViewModelName(), getModuleName(), @@ -186,10 +189,4 @@ private String getNamespace() { ); return parts[0] + Package.fqnSeparator + parts[1] + Package.fqnSeparator + directoryPart; } - - @Override - public void onCancel() { - // add your code here if necessary - dispose(); - } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewWebApiDeclarationDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewWebApiDeclarationDialog.java index d9f06a883..84a361ae4 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewWebApiDeclarationDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/NewWebApiDeclarationDialog.java @@ -141,16 +141,13 @@ public static void open( * Fire generation process if all fields are valid. */ private void onOK() { - if (!validateFormFields()) { - return; + if (validateFormFields()) { + new WebApiDeclarationGenerator( + getDialogDataObject(), + project + ).generate(NewWebApiDeclarationAction.ACTION_NAME, true); } - - new WebApiDeclarationGenerator( - getDialogDataObject(), - project - ).generate(NewWebApiDeclarationAction.ACTION_NAME, true); - - this.setVisible(false); + exit(); } /** diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideClassByAPreferenceDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideClassByAPreferenceDialog.java index 07d1b1448..d1e7ea551 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideClassByAPreferenceDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideClassByAPreferenceDialog.java @@ -168,6 +168,7 @@ private void fillTargetAreaOptions() { protected void onOK() { if (!validateFormFields()) { + exit(); return; } final PsiFile diXml = new PreferenceDiXmlGenerator(new PreferenceDiXmFileData( @@ -203,7 +204,7 @@ protected void onOK() { isInterface ), project).generate(OverrideClassByAPreferenceAction.ACTION_NAME, true); - this.setVisible(false); + exit(); } public String getPreferenceClassName() { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideInThemeDialog.java b/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideInThemeDialog.java index 5902991fd..1e3133b53 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideInThemeDialog.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/dialog/OverrideInThemeDialog.java @@ -13,6 +13,7 @@ import com.magento.idea.magento2plugin.actions.generation.dialog.validator.rule.NotEmptyRule; import com.magento.idea.magento2plugin.actions.generation.generator.OverrideInThemeGenerator; import com.magento.idea.magento2plugin.indexes.ModuleIndex; +import com.magento.idea.magento2plugin.magento.packages.Areas; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; @@ -95,15 +96,13 @@ private void onExtend() { } private void onOK() { - if (!validateFormFields()) { - return; - } - - final OverrideInThemeGenerator overrideInThemeGenerator = - new OverrideInThemeGenerator(project); - overrideInThemeGenerator.execute(psiFile, this.getTheme(), this.isOverride()); + if (validateFormFields()) { + final OverrideInThemeGenerator overrideInThemeGenerator = + new OverrideInThemeGenerator(project); - this.setVisible(false); + overrideInThemeGenerator.execute(psiFile, this.getTheme(), this.isOverride()); + } + exit(); } public String getTheme() { @@ -133,9 +132,13 @@ public static void open(final @NotNull Project project, final PsiFile psiFile) { } private void fillThemeOptions() { + final String area = psiFile.getVirtualFile().getPath().split("view/")[1].split("/")[0]; final List themeNames = new ModuleIndex(project).getEditableThemeNames(); - for (final String themeName: themeNames) { - theme.addItem(themeName); + + for (final String themeName : themeNames) { + if (Areas.base.toString().equals(area) || themeName.split("/")[0].equals(area)) { + theme.addItem(themeName); + } } } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/CLICommandClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/CLICommandClassGenerator.java index 7e00fe79a..862688f65 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/CLICommandClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/CLICommandClassGenerator.java @@ -18,6 +18,7 @@ import com.magento.idea.magento2plugin.magento.files.CLICommandTemplate; import java.util.Properties; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @SuppressWarnings({ "PMD.AvoidUncheckedExceptionsInSignatures", @@ -69,11 +70,17 @@ public PsiFile generate(final String actionName) throws RuntimeException { return cliCommandFile; } - private PhpFile createCLICommandClass(final String actionName) { + private @Nullable PhpFile createCLICommandClass(final String actionName) { + final PsiDirectory parentDirectory = getParentDirectory(); + + if (parentDirectory == null) { + return null; + } + final PsiFile cliCommandFile = fileGenerator.generate( this.getCLICommandTemplate(), getAttributes(), - this.getParentDirectory(), + parentDirectory, actionName ); @@ -82,9 +89,14 @@ private PhpFile createCLICommandClass(final String actionName) { private PsiDirectory getParentDirectory() { final String moduleName = this.phpClassData.getModuleName(); - final String[] subDirectories = this.phpClassData.getParentDirectory().split("/"); PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } + final String[] subDirectories = this.phpClassData.getParentDirectory().split("/"); + for (final String subDirectory : subDirectories) { parentDirectory = dirGenerator.findOrCreateSubdirectory(parentDirectory, subDirectory); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/CronjobClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/CronjobClassGenerator.java index 49010dd5e..0b1ea3350 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/CronjobClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/CronjobClassGenerator.java @@ -89,12 +89,16 @@ protected void fillAttributes(final Properties attributes) { * @return PhpFile */ private PhpFile createCronjobClass(final String actionName) { - final String cronjobClassName = this.cronjobClassData.getClassName(); final String moduleName = this.cronjobClassData.getModuleName(); - final String[] cronjobSubDirectories = this.cronjobClassData.getDirectory().split("/"); PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(moduleName); + if (parentDirectory == null) { + return null; + } + final String cronjobClassName = this.cronjobClassData.getClassName(); + final String[] cronjobSubDirectories = this.cronjobClassData.getDirectory().split("/"); + for (final String cronjobSubDirectory: cronjobSubDirectories) { parentDirectory = directoryGenerator .findOrCreateSubdirectory(parentDirectory, cronjobSubDirectory); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/DbSchemaXmlGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/DbSchemaXmlGenerator.java index f394ebde5..fb91e1fbc 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/DbSchemaXmlGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/DbSchemaXmlGenerator.java @@ -15,23 +15,28 @@ import com.intellij.psi.xml.XmlTag; import com.magento.idea.magento2plugin.actions.generation.data.DbSchemaXmlData; import com.magento.idea.magento2plugin.actions.generation.generator.util.FindOrCreateDbSchemaXmlUtil; +import com.magento.idea.magento2plugin.bundles.CommonBundle; +import com.magento.idea.magento2plugin.bundles.ValidatorBundle; import com.magento.idea.magento2plugin.magento.files.ModuleDbSchemaXml; import com.magento.idea.magento2plugin.magento.packages.database.ColumnAttributes; import com.magento.idea.magento2plugin.magento.packages.database.TableColumnTypes; import java.util.HashMap; -import java.util.InputMismatchException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; +import javax.swing.JOptionPane; import org.jetbrains.annotations.NotNull; public class DbSchemaXmlGenerator extends FileGenerator { + private final Project project; private final String moduleName; private final DbSchemaXmlData dbSchemaXmlData; private final FindOrCreateDbSchemaXmlUtil findOrCreateDbSchemaXmlUtil; + private final ValidatorBundle validatorBundle; + private final CommonBundle commonBundle; private final List newTagsQueue; private final Map newTagsChildParentRelationMap; @@ -52,6 +57,8 @@ public DbSchemaXmlGenerator( this.project = project; this.moduleName = moduleName; this.dbSchemaXmlData = dbSchemaXmlData; + this.validatorBundle = new ValidatorBundle(); + this.commonBundle = new CommonBundle(); findOrCreateDbSchemaXmlUtil = new FindOrCreateDbSchemaXmlUtil(project); newTagsQueue = new LinkedList<>(); @@ -62,6 +69,7 @@ public DbSchemaXmlGenerator( @SuppressWarnings({ "PMD.NPathComplexity", "PMD.CyclomaticComplexity", + "PMD.CognitiveComplexity", "PMD.ExcessiveImports", "PMD.AvoidInstantiatingObjectsInLoops" }) @@ -99,32 +107,39 @@ public PsiFile generate(final String actionName) { primaryKeyData.putAll(columnData); } + final String columnName = columnData.get(ColumnAttributes.NAME.getName()); final String columnTypeValue = columnData.get(ColumnAttributes.TYPE.getName()); final TableColumnTypes columnType = TableColumnTypes.getByValue(columnTypeValue); if (columnType == null) { - throw new InputMismatchException( - "Invalid column types provided. Should be compatible with " - + TableColumnTypes.class + final String errorMessage = validatorBundle.message( + "validator.dbSchema.invalidColumnType", + columnName == null ? "" : columnName + + ); + JOptionPane.showMessageDialog( + null, + errorMessage, + commonBundle.message("common.error"), + JOptionPane.ERROR_MESSAGE ); + return null; } final Map attributes = new LinkedHashMap<>(); final List allowedColumns = ModuleDbSchemaXml.getAllowedAttributes(columnType); + for (final Map.Entry columnDataEntry : columnData.entrySet()) { if (allowedColumns.contains(columnDataEntry.getKey()) && !columnDataEntry.getValue().isEmpty()) { attributes.put(columnDataEntry.getKey(), columnDataEntry.getValue()); } } - final String columnIdentityValue = - columnData.get(ColumnAttributes.NAME.getName()); - findOrCreateTag( ModuleDbSchemaXml.XML_TAG_COLUMN, ColumnAttributes.NAME.getName(), tableTag, - columnIdentityValue, + columnName, attributes ); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/MessageQueueClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/MessageQueueClassGenerator.java index 52eb307dc..f22a65a6a 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/MessageQueueClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/MessageQueueClassGenerator.java @@ -21,10 +21,13 @@ import com.magento.idea.magento2plugin.magento.packages.File; import com.magento.idea.magento2plugin.util.GetFirstClassOfFile; import com.magento.idea.magento2plugin.util.GetPhpClassByFQN; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; import javax.swing.JOptionPane; public class MessageQueueClassGenerator extends FileGenerator { + private final MessageQueueClassData messageQueueClassDataName; private final Project project; private final DirectoryGenerator directoryGenerator; @@ -33,6 +36,7 @@ public class MessageQueueClassGenerator extends FileGenerator { private final CommonBundle commonBundle; private final String moduleName; private final GetFirstClassOfFile getFirstClassOfFile; + private final List errors = new ArrayList<>(); /** * Message queue handler constructor. @@ -68,40 +72,34 @@ public PsiFile generate(final String actionName) { ); if (handler != null) { - final String errorMessage = this.validatorBundle.message( + errors.add(validatorBundle.message( "validator.file.alreadyExists", "Handler Class" - ); - JOptionPane.showMessageDialog( - null, - errorMessage, - commonBundle.message("common.error"), - JOptionPane.ERROR_MESSAGE - ); - + )); return; } - handler = createHandlerClass(actionName); if (handler == null) { - final String errorMessage = this.validatorBundle.message( + errors.add(validatorBundle.message( "validator.file.cantBeCreated", "Handler Class" - ); - JOptionPane.showMessageDialog( - null, - errorMessage, - commonBundle.message("common.error"), - JOptionPane.ERROR_MESSAGE - ); - + )); return; } handlerFiles[0] = handler.getContainingFile(); }); + for (final String errorMessage : errors) { + JOptionPane.showMessageDialog( + null, + errorMessage, + commonBundle.message("common.error"), + JOptionPane.ERROR_MESSAGE + ); + } + return handlerFiles[0]; } @@ -114,6 +112,10 @@ protected void fillAttributes(final Properties attributes) { private PhpClass createHandlerClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(this.moduleName); + + if (parentDirectory == null) { + return null; + } final PsiFile handlerFile; final String[] handlerDirectories = messageQueueClassDataName.getPath().split( File.separator diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleBlockClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleBlockClassGenerator.java index d6b7e31e8..9a3b09b2c 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleBlockClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleBlockClassGenerator.java @@ -58,6 +58,7 @@ public ModuleBlockClassGenerator( * @param actionName String * @return PsiFile */ + @Override public PsiFile generate(final String actionName) { final String errorTitle = commonBundle.message("common.error"); final PhpClass block = GetPhpClassByFQN.getInstance(project).execute(getBlockFqn()); @@ -106,7 +107,12 @@ private String getBlockFqn() { private PhpFile createBlockClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(getBlockModule()); + + if (parentDirectory == null) { + return null; + } final String[] blockDirectories = blockFileData.getBlockDirectory().split(File.separator); + for (final String blockDirectory: blockDirectories) { parentDirectory = directoryGenerator.findOrCreateSubdirectory( parentDirectory, @@ -127,6 +133,7 @@ private PhpFile createBlockClass(final String actionName) { return (PhpFile) blockFile; } + @Override protected void fillAttributes(final Properties attributes) { final String blockClassName = blockFileData.getBlockClassName(); attributes.setProperty("NAME", blockClassName); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleComposerJsonGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleComposerJsonGenerator.java index 736287dc4..85e867ec6 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleComposerJsonGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleComposerJsonGenerator.java @@ -5,12 +5,13 @@ package com.magento.idea.magento2plugin.actions.generation.generator; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; +import com.intellij.json.psi.JsonFile; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; import com.magento.idea.magento2plugin.actions.generation.data.ModuleComposerJsonData; import com.magento.idea.magento2plugin.actions.generation.generator.data.ModuleDirectoriesData; import com.magento.idea.magento2plugin.actions.generation.generator.util.DirectoryGenerator; @@ -18,11 +19,12 @@ import com.magento.idea.magento2plugin.indexes.ModuleIndex; import com.magento.idea.magento2plugin.magento.files.ComposerJson; import com.magento.idea.magento2plugin.util.CamelCaseToHyphen; -import java.io.FileNotFoundException; -import java.io.FileReader; import java.util.List; import java.util.Properties; import org.jetbrains.annotations.NotNull; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; public class ModuleComposerJsonGenerator extends FileGenerator { @@ -120,8 +122,8 @@ private String getDependenciesString(final List dependenciesList) { final Object[] dependencies = dependenciesList.toArray(); result = result.concat(ComposerJson.DEFAULT_DEPENDENCY); final boolean noDependency = - dependencies.length == 1 && dependencies[0].equals( - ComposerJson.NO_DEPENDENCY_LABEL + dependencies.length == 1 && ComposerJson.NO_DEPENDENCY_LABEL.equals( + dependencies[0] ); if (dependencies.length == 0 || noDependency) { result = result.concat("\n"); @@ -161,34 +163,46 @@ private Pair getDependencyData( "_-", "/" ); try { - final PsiFile virtualFile = moduleIndex.getModuleDirectoryByModuleName(dependency) - .findFile(ComposerJson.FILE_NAME); + final PsiDirectory moduleDir = moduleIndex.getModuleDirectoryByModuleName(dependency); + + if (moduleDir == null) { + return Pair.create("", ""); + } + final PsiFile virtualFile = moduleDir.findFile(ComposerJson.FILE_NAME); if (virtualFile != null) { //NOPMD - final VirtualFile composerJsonFile = virtualFile.getVirtualFile(); - if (composerJsonFile.exists()) { - final JsonElement jsonElement = - new JsonParser().parse( - new FileReader(composerJsonFile.getPath())//NOPMD - ); - final JsonElement versionJsonElement = - jsonElement.getAsJsonObject().get("version"); - final JsonElement nameJsonElement = jsonElement.getAsJsonObject().get("name"); + final VirtualFile composerJsonVirtualFile = virtualFile.getVirtualFile(); + + if (composerJsonVirtualFile.exists()) { + final PsiFile composerJsonFile = PsiManager.getInstance(project) + .findFile(composerJsonVirtualFile); + if (!(composerJsonFile instanceof JsonFile)) { + return Pair.create("", ""); + } + final JSONParser parser = new JSONParser(); + final Object obj = parser.parse( + composerJsonFile.getText() + ); + final JSONObject jsonObject = (JSONObject) obj; + final String versionJsonElement = jsonObject.get("version").toString(); + final String nameJsonElement = jsonObject.get("name").toString(); + if (versionJsonElement != null) { - version = versionJsonElement.getAsString(); + version = versionJsonElement; final int minorVersionSeparator = version.lastIndexOf('.'); version = new StringBuilder(version) .replace(minorVersionSeparator + 1, version.length(),"*") .toString(); } + if (nameJsonElement != null) { - moduleName = nameJsonElement.getAsString(); + moduleName = nameJsonElement; } } } else { return Pair.create("", ""); } - } catch (FileNotFoundException e) { //NOPMD + } catch (ParseException exception) { //NOPMD // It's fine } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleControllerClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleControllerClassGenerator.java index a5142cb3d..a2daf2286 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleControllerClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleControllerClassGenerator.java @@ -31,6 +31,7 @@ import java.util.Arrays; import java.util.List; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.JOptionPane; public class ModuleControllerClassGenerator extends FileGenerator { @@ -73,6 +74,8 @@ public ModuleControllerClassGenerator( @Override public PsiFile generate(final String actionName) { final PsiFile[] controllerFiles = new PsiFile[1]; + final AtomicBoolean isControllerExists = new AtomicBoolean(false); + final AtomicBoolean isControllerCanNotBeCreated = new AtomicBoolean(false); WriteCommandAction.runWriteCommandAction(project, () -> { PhpClass controller = GetPhpClassByFQN.getInstance(project).execute( @@ -80,40 +83,40 @@ public PsiFile generate(final String actionName) { ); if (controller != null) { - final String errorMessage = this.validatorBundle.message( - "validator.file.alreadyExists", - "Controller Class" - ); - JOptionPane.showMessageDialog( - null, - errorMessage, - commonBundle.message("common.error"), - JOptionPane.ERROR_MESSAGE - ); - + isControllerExists.set(true); return; } - controller = createControllerClass(actionName); if (controller == null) { - final String errorMessage = this.validatorBundle.message( - "validator.file.cantBeCreated", - "Controller Class" - ); - JOptionPane.showMessageDialog( - null, - errorMessage, - commonBundle.message("common.error"), - JOptionPane.ERROR_MESSAGE - ); - + isControllerCanNotBeCreated.set(true); return; } - controllerFiles[0] = controller.getContainingFile(); }); + if (isControllerExists.get()) { + JOptionPane.showMessageDialog( + null, + validatorBundle.message( + "validator.file.alreadyExists", + "Controller Class" + ), + commonBundle.message("common.error"), + JOptionPane.ERROR_MESSAGE + ); + } else if (isControllerCanNotBeCreated.get()) { + JOptionPane.showMessageDialog( + null, + validatorBundle.message( + "validator.file.cantBeCreated", + "Controller Class" + ), + commonBundle.message("common.error"), + JOptionPane.ERROR_MESSAGE + ); + } + return controllerFiles[0]; } @@ -148,6 +151,10 @@ private String getControllerFqn() { private PhpClass createControllerClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(getControllerModule()); + + if (parentDirectory == null) { + return null; + } final PsiFile controllerFile; final String[] controllerDirectories = data.getActionDirectory().split( File.separator diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleEmailTemplateHtmlGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleEmailTemplateHtmlGenerator.java index babb32fa7..f3e53801a 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleEmailTemplateHtmlGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleEmailTemplateHtmlGenerator.java @@ -51,6 +51,7 @@ public ModuleEmailTemplateHtmlGenerator( * @param actionName Action name * @return PsiFile */ + @Override public PsiFile generate(final String actionName) { final PsiFile templateFile = FileBasedIndexUtil.findModuleViewFile( this.emailTemplateData.getFileName(), @@ -67,6 +68,10 @@ public PsiFile generate(final String actionName) { PsiDirectory parentDirectory = this.moduleIndex.getModuleDirectoryByModuleName( this.emailTemplateData.getModule() ); + + if (parentDirectory == null) { + return null; + } final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleViewDir); @@ -96,7 +101,7 @@ protected void fillAttributes(final Properties attributes) { attributes.setProperty("SUBJECT", emailTemplateData.getSubject()); attributes.setProperty("TYPE", emailTemplateData.getType()); - if (emailTemplateData.getType().equals(EmailTemplateHtml.HTML_TYPE)) { + if (EmailTemplateHtml.HTML_TYPE.equals(emailTemplateData.getType())) { attributes.setProperty("HTML_TYPE", "true"); } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleGraphQlResolverClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleGraphQlResolverClassGenerator.java index beb89cef1..b87da10d9 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleGraphQlResolverClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleGraphQlResolverClassGenerator.java @@ -117,7 +117,7 @@ private int getInsertPos(final PhpClass graphQlResolverClass) { LeafPsiElement.class ); for (final LeafPsiElement leafPsiElement: leafElements) { - if (!leafPsiElement.getText().equals(MagentoPhpClass.CLOSING_TAG)) { + if (!MagentoPhpClass.CLOSING_TAG.equals(leafPsiElement.getText())) { continue; } insertPos = leafPsiElement.getTextOffset(); @@ -128,6 +128,10 @@ private int getInsertPos(final PhpClass graphQlResolverClass) { private PhpClass createGraphQlResolverClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(graphQlResolverFileData.getGraphQlResolverModule()); + + if (parentDirectory == null) { + return null; + } final String[] graphQlResolverDirectories = graphQlResolverFileData .getGraphQlResolverDirectory().split(File.separator); for (final String graphQlResolverDirectory: graphQlResolverDirectories) { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleViewModelClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleViewModelClassGenerator.java index a83ba7724..0313ebb1c 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleViewModelClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ModuleViewModelClassGenerator.java @@ -58,6 +58,7 @@ public ModuleViewModelClassGenerator( * @param actionName String * @return PsiFile */ + @Override public PsiFile generate(final String actionName) { final PhpClass block = GetPhpClassByFQN.getInstance(project).execute(getViewModelFqn()); final String errorTitle = commonBundle.message("common.error"); @@ -106,6 +107,10 @@ private String getViewModelFqn() { private PhpFile createViewModelClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(getViewModelModule()); + + if (parentDirectory == null) { + return null; + } final String[] viewModelDirectories = viewModelFileData.getViewModelDirectory() .split(File.separator); for (final String viewModelDirectory: viewModelDirectories) { @@ -128,6 +133,7 @@ private PhpFile createViewModelClass(final String actionName) { return (PhpFile) viewModelFile; } + @Override protected void fillAttributes(final Properties attributes) { final String viewModelClassName = viewModelFileData.getViewModelClassName(); attributes.setProperty("NAME", viewModelClassName); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/NewEntityLayoutGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/NewEntityLayoutGenerator.java index 4587a05d2..7fdfe0f47 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/NewEntityLayoutGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/NewEntityLayoutGenerator.java @@ -88,6 +88,10 @@ public PsiFile generate(final @NotNull String actionName) { final PsiDirectory moduleBaseDir = moduleIndex.getModuleDirectoryByModuleName( data.getModuleName() ); + + if (moduleBaseDir == null) { + return null; + } final PsiDirectory layoutBaseDir = directoryGenerator.findOrCreateSubdirectories( moduleBaseDir, file.getDirectory() diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/ObserverClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/ObserverClassGenerator.java index da453a7a7..8ecfe692e 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/ObserverClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/ObserverClassGenerator.java @@ -122,7 +122,7 @@ private int getInsertPos(final PhpClass observerClass) { LeafPsiElement.class ); for (final LeafPsiElement leafPsiElement: leafElements) { - if (!leafPsiElement.getText().equals(MagentoPhpClass.CLOSING_TAG)) { + if (!MagentoPhpClass.CLOSING_TAG.equals(leafPsiElement.getText())) { continue; } insertPos = leafPsiElement.getTextOffset(); @@ -133,6 +133,10 @@ private int getInsertPos(final PhpClass observerClass) { private PhpClass createObserverClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(observerFileData.getObserverModule()); + + if (parentDirectory == null) { + return null; + } final String[] observerDirectories = observerFileData.getObserverDirectory() .split(File.separator); for (final String observerDirectory: observerDirectories) { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/OverrideInThemeGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/OverrideInThemeGenerator.java index 4be05b573..94f092bb2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/OverrideInThemeGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/OverrideInThemeGenerator.java @@ -69,6 +69,10 @@ public void execute(final PsiFile baseFile, final String themeName, final boolea final ModuleIndex moduleIndex = new ModuleIndex(project); PsiDirectory directory = moduleIndex.getModuleDirectoryByModuleName(themeName); + + if (directory == null) { + return; + } directory = getTargetDirectory(directory, pathComponents); if (directory.findFile(baseFile.getName()) != null) { @@ -134,11 +138,13 @@ private PsiDirectory getTargetDirectory( PsiDirectory directory, //NOPMD final List pathComponents ) { + PsiDirectory result = directory; final DirectoryGenerator generator = DirectoryGenerator.getInstance(); + for (final String directoryName : pathComponents) { - directory = generator.findOrCreateSubdirectory(directory, directoryName); + result = generator.findOrCreateSubdirectory(directory, directoryName); } - return directory; + return result; } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/PhpFileGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/PhpFileGenerator.java index 2e7730f08..dccd91be2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/PhpFileGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/PhpFileGenerator.java @@ -77,8 +77,16 @@ public PsiFile generate(final @NotNull String actionName) { return phpClass.getContainingFile(); } + final PsiDirectory moduleDirectory = moduleIndex.getModuleDirectoryByModuleName( + file.getModuleName() + ); + + if (moduleDirectory == null) { + onFileGenerated(null, actionName); + return null; + } final PsiDirectory fileBaseDir = directoryGenerator.findOrCreateSubdirectories( - moduleIndex.getModuleDirectoryByModuleName(file.getModuleName()), + moduleDirectory, file.getDirectory() ); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/PluginClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/PluginClassGenerator.java index 0ee99ae86..5930bbc4c 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/PluginClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/PluginClassGenerator.java @@ -5,6 +5,7 @@ package com.magento.idea.magento2plugin.actions.generation.generator; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; @@ -88,6 +89,7 @@ public PluginClassGenerator( * * @return PsiFile */ + @SuppressWarnings({"PMD.CognitiveComplexity", "PMD.ExcessiveMethodLength"}) @Override public PsiFile generate(final String actionName) { final PsiFile[] pluginFile = {null}; @@ -99,15 +101,27 @@ public PsiFile generate(final String actionName) { pluginClass = createPluginClass(actionName); } if (pluginClass == null) { - final String errorMessage = validatorBundle.message( - "validator.file.cantBeCreated", - "Plugin Class" - ); - JOptionPane.showMessageDialog( - null, - errorMessage, - errorTitle, - JOptionPane.ERROR_MESSAGE + String errorMessage; + + if (fileFromTemplateGenerator.getLastExceptionMessage() == null) { + errorMessage = validatorBundle.message( + "validator.file.cantBeCreated", + "Plugin Class" + ); + } else { + errorMessage = validatorBundle.message( + "validator.file.cantBeCreatedWithException", + "Plugin Class", + fileFromTemplateGenerator.getLastExceptionMessage() + ); + } + ApplicationManager.getApplication().invokeLater( + () -> JOptionPane.showMessageDialog( + null, + errorMessage, + errorTitle, + JOptionPane.ERROR_MESSAGE + ) ); return; @@ -131,11 +145,13 @@ public PsiFile generate(final String actionName) { "validator.file.alreadyExists", "Plugin Class" ); - JOptionPane.showMessageDialog( - null, - errorMessage, - errorTitle, - JOptionPane.ERROR_MESSAGE + ApplicationManager.getApplication().invokeLater( + () -> JOptionPane.showMessageDialog( + null, + errorMessage, + errorTitle, + JOptionPane.ERROR_MESSAGE + ) ); return; @@ -206,6 +222,10 @@ private boolean checkIfMethodExist( private PhpClass createPluginClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(getPluginModule()); + + if (parentDirectory == null) { + return null; + } final String[] pluginDirectories = pluginFileData.getPluginDirectory() .split(File.separator); for (final String pluginDirectory: pluginDirectories) { @@ -262,7 +282,7 @@ private int getInsertPos(final PhpClass pluginClass) { } for (final LeafPsiElement leafPsiElement: leafElements) { - if (!leafPsiElement.getText().equals(MagentoPhpClass.CLOSING_TAG)) { + if (!MagentoPhpClass.CLOSING_TAG.equals(leafPsiElement.getText())) { continue; } insertPos = leafPsiElement.getTextOffset(); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/PreferenceClassGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/PreferenceClassGenerator.java index 9e8c2f0c6..dc62f8f71 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/PreferenceClassGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/PreferenceClassGenerator.java @@ -82,6 +82,10 @@ public PsiFile generate(final String actionName) { private PhpClass createPluginClass(final String actionName) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(getPreferenceModule()); + + if (parentDirectory == null) { + return null; + } final String[] pluginDirectories = preferenceFileData.getPreferenceDirectory() .split(File.separator); for (final String pluginDirectory: pluginDirectories) { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/QueryGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/QueryGenerator.java index 1fd09ef21..92984eb5c 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/QueryGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/QueryGenerator.java @@ -117,6 +117,10 @@ public PsiFile generate(final @NotNull String actionName) { private PhpClass createDataProviderClass(final @NotNull String actionName) { final PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(this.moduleName); + + if (parentDirectory == null) { + return null; + } final PsiDirectory dataProviderDirectory = directoryGenerator.findOrCreateSubdirectories(parentDirectory, data.getPath()); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormButtonBlockGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormButtonBlockGenerator.java index 3015e34e8..164d0153f 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormButtonBlockGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormButtonBlockGenerator.java @@ -123,6 +123,10 @@ public PsiFile generate(final @NotNull String actionName) { final PsiDirectory moduleBaseDir = moduleIndex.getModuleDirectoryByModuleName( buttonData.getButtonModule() ); + + if (moduleBaseDir == null) { + return null; + } final PsiDirectory baseDirectory = directoryGenerator.findOrCreateSubdirectories( moduleBaseDir, buttonData.getButtonDirectory() diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormGenerator.java index 5a5d3e5cb..1e41dc0d2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentFormGenerator.java @@ -92,14 +92,16 @@ protected void generateButtonClasses(final @NotNull String actionName) { protected PsiFile createForm( final String actionName ) { - final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); - final FileFromTemplateGenerator fileFromTemplateGenerator = - new FileFromTemplateGenerator(project); - final String moduleName = data.getModuleName(); final PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(moduleName); + if (parentDirectory == null) { + return null; + } + final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); + final FileFromTemplateGenerator fileFromTemplateGenerator = + new FileFromTemplateGenerator(project); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleViewDir); final String area = data.getFormArea(); @@ -147,6 +149,14 @@ protected PsiFile createForm( protected void fillAttributes(final @NotNull Properties attributes) { final PhpClassTypesBuilder phpClassTypesBuilder = new PhpClassTypesBuilder(); + if (data.getFields().isEmpty()) { + phpClassTypesBuilder + .appendProperty("PRIMARY_FIELD", ""); + } else { + phpClassTypesBuilder + .appendProperty("PRIMARY_FIELD", data.getFields().get(0).getName()); + } + phpClassTypesBuilder .appendProperty("NAME", data.getFormName()) .appendProperty("LABEL", data.getLabel()) @@ -163,7 +173,6 @@ protected void fillAttributes(final @NotNull Properties attributes) { data.getDataProviderPath() ).getClassFqn() ) - .appendProperty("PRIMARY_FIELD", data.getFields().get(0).getName()) .mergeProperties(attributes); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentGridXmlGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentGridXmlGenerator.java index ef457393d..4b75ed7f5 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentGridXmlGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/UiComponentGridXmlGenerator.java @@ -67,6 +67,9 @@ public PsiFile generate(final String actionName) { final PsiDirectory parentDirectory = moduleIndex.getModuleDirectoryByModuleName( moduleName ); + if (parentDirectory == null) { + return null; + } final String subdirectory = String.format( "%s/%s/%s", Package.moduleViewDir, diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/code/util/ConvertPluginParamsToString.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/code/util/ConvertPluginParamsToString.java index c9d391603..004f6b0f0 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/code/util/ConvertPluginParamsToString.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/code/util/ConvertPluginParamsToString.java @@ -7,6 +7,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.util.text.Strings; import com.intellij.psi.PsiElement; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.config.PhpLanguageFeature; @@ -42,7 +43,12 @@ private ConvertPluginParamsToString() {} * * @return String */ - @SuppressWarnings({"PMD.NPathComplexity", "PMD.CyclomaticComplexity", "PMD.ConfusingTernary"}) + @SuppressWarnings({ + "PMD.NPathComplexity", + "PMD.CyclomaticComplexity", + "PMD.CognitiveComplexity", + "PMD.ConfusingTernary" + }) public static String execute( final Collection parameters, final @NotNull Plugin.PluginType type, @@ -52,7 +58,11 @@ public static String execute( String returnType = PhpTypeMetadataParserUtil.getMethodReturnType(myMethod); if (returnType != null && PhpClassGeneratorUtil.isValidFqn(returnType)) { - returnType = PhpClassGeneratorUtil.getNameFromFqn(returnType); + if (Strings.endsWith(returnType, "[]")) { + returnType = "array"; + } else { + returnType = PhpClassGeneratorUtil.getNameFromFqn(returnType); + } } final Iterator parametersIterator = parameters.iterator(); int iterator = 0; @@ -66,7 +76,19 @@ public static String execute( if (element instanceof Parameter) { String parameterText = PhpCodeUtil.paramToString(element); - if (parameterText.contains(Package.fqnSeparator)) { + // Parameter has default value. + if (parameterText.contains("=")) { + final String[] paramParts = parameterText.split("="); + parameterText = paramParts[0]; + parameterText += " = ";//NOPMD + String defaultValue = paramParts[1]; + + if (defaultValue.contains(Package.fqnSeparator)) { + final String[] fqnArray = defaultValue.split("\\\\"); + defaultValue = fqnArray[fqnArray.length - 1]; + } + parameterText += defaultValue;//NOPMD + } else if (parameterText.contains(Package.fqnSeparator)) { final String[] fqnArray = parameterText.split("\\\\"); parameterText = fqnArray[fqnArray.length - 1]; } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FileFromTemplateGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FileFromTemplateGenerator.java index a7aad6da3..8aac17670 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FileFromTemplateGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FileFromTemplateGenerator.java @@ -12,7 +12,6 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; @@ -31,9 +30,11 @@ import org.jetbrains.annotations.Nullable; public class FileFromTemplateGenerator { - private final Project project; - public FileFromTemplateGenerator(final Project project) { + private final @NotNull Project project; + private @Nullable String exceptionMessage; + + public FileFromTemplateGenerator(final @NotNull Project project) { this.project = project; } @@ -44,10 +45,10 @@ public FileFromTemplateGenerator(final Project project) { * @param attributes Properties * @param baseDir PsiDirectory * @param actionName String + * * @return PsiFile */ - @Nullable - public PsiFile generate( + public @Nullable PsiFile generate( final @NotNull ModuleFileInterface moduleFile, final @NotNull Properties attributes, final @NotNull PsiDirectory baseDir, @@ -55,16 +56,19 @@ public PsiFile generate( ) { final Ref fileRef = new Ref<>(null); final Ref exceptionRef = new Ref<>(null); + exceptionMessage = null;//NOPMD final String filePath = baseDir.getText().concat("/").concat(moduleFile.getFileName()); + CommandProcessor.getInstance().executeCommand(project, () -> { final Runnable run = () -> { try { - PsiFile file = createFile(moduleFile, filePath, baseDir, attributes); + final PsiFile file = createFile(moduleFile, filePath, baseDir, attributes); + if (file != null) { fileRef.set(file); } - } catch (IncorrectOperationException | IOException var9) { - exceptionRef.set(var9.getMessage()); + } catch (IncorrectOperationException | IOException exception) { + exceptionRef.set(exception.getMessage()); } }; ApplicationManager.getApplication().runWriteAction(run); @@ -73,11 +77,20 @@ public PsiFile generate( if (exceptionRef.isNull()) { return fileRef.get(); } + exceptionMessage = exceptionRef.get(); - Messages.showErrorDialog(exceptionRef.get(), actionName); return null; } + /** + * Get last thrown exception message if exists. + * + * @return String + */ + public @Nullable String getLastExceptionMessage() { + return exceptionMessage; + } + @Nullable private PsiFile createFile( final @NotNull ModuleFileInterface moduleFile, @@ -89,13 +102,19 @@ private PsiFile createFile( final String fileName = path.get(path.size() - 1); final PsiFile fileTemplate = createFileFromTemplate( getTemplateManager(), - baseDir, moduleFile.getTemplate(), attributes, fileName, moduleFile.getLanguage()); + baseDir, + moduleFile.getTemplate(), + attributes, + fileName, + moduleFile.getLanguage() + ); + if (fileTemplate == null) { throw new IncorrectOperationException("Template not found!"); } else { PsiElement file; - file = baseDir.add(fileTemplate); + if (file instanceof PsiFile) { return (PsiFile)file; } else { @@ -125,6 +144,7 @@ public PsiFile createFileFromTemplate( final @NotNull Language language ) throws IOException { FileTemplate fileTemplate; + try { fileTemplate = templateManager.getInternalTemplate(templateName); } catch (IllegalStateException e) { @@ -140,6 +160,7 @@ public PsiFile createFileFromTemplate( true, false ); + if (fileTemplate.isReformatCode()) { CodeStyleManager.getInstance(project).reformat(file); } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateAclXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateAclXml.java index 5a76a27f4..94c649e2b 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateAclXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateAclXml.java @@ -31,12 +31,15 @@ public FindOrCreateAclXml(final Project project) { * @return PsiFile */ public PsiFile execute(final String actionName, final String moduleName) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); parentDirectory = directoryGenerator .findOrCreateSubdirectory(parentDirectory, Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCronGroupXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCronGroupXml.java index 40f1bf0ac..9961ecaa0 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCronGroupXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCronGroupXml.java @@ -45,6 +45,10 @@ public FindOrCreateCronGroupXml(final Project project) { */ public PsiFile execute(final String actionName, final String moduleName) { PsiDirectory parentDirectory = this.moduleIndex.getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCrontabXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCrontabXml.java index 6a0e4800d..6d5251ccf 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCrontabXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateCrontabXml.java @@ -45,6 +45,10 @@ public FindOrCreateCrontabXml(final Project project) { */ public PsiFile execute(final String actionName, final String moduleName) { PsiDirectory parentDirectory = this.moduleIndex.getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaWhitelistJson.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaWhitelistJson.java index 01c5258a2..676892255 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaWhitelistJson.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaWhitelistJson.java @@ -54,6 +54,10 @@ public PsiFile execute(final @NotNull String actionName, final @NotNull String m if (dbSchemaWhitelistJson == null) { PsiDirectory parentDirectory = new ModuleIndex(project) .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } parentDirectory = directoryGenerator .findOrCreateSubdirectory(parentDirectory, Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaXmlUtil.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaXmlUtil.java index 2d70471ac..6625a5982 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaXmlUtil.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDbSchemaXmlUtil.java @@ -31,12 +31,15 @@ public FindOrCreateDbSchemaXmlUtil(final Project project) { * @return PsiFile */ public PsiFile execute(final String actionName, final String moduleName) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); parentDirectory = directoryGenerator .findOrCreateSubdirectory(parentDirectory, Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDiXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDiXml.java index 854b59358..e16e63743 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDiXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateDiXml.java @@ -32,12 +32,15 @@ public FindOrCreateDiXml(final Project project) { * @return PsiFile */ public PsiFile execute(final String actionName, final String moduleName, final String area) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); if (!getArea(area).equals(Areas.base)) { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEmailTemplatesXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEmailTemplatesXml.java index f37e0e75b..480707829 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEmailTemplatesXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEmailTemplatesXml.java @@ -45,6 +45,10 @@ public FindOrCreateEmailTemplatesXml(final Project project) { */ public PsiFile execute(final String actionName, final String moduleName) { PsiDirectory parentDirectory = this.moduleIndex.getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEventsXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEventsXml.java index 23d44f2b1..5322cb9b0 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEventsXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateEventsXml.java @@ -36,11 +36,15 @@ public PsiFile execute( final String moduleName, final String area ) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + if (parentDirectory == null) { + return null; + } + final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); if (!getArea(area).equals(Areas.base)) { diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateLayoutXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateLayoutXml.java index e77bebfdd..177059235 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateLayoutXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateLayoutXml.java @@ -43,12 +43,15 @@ public PsiFile execute( final String moduleName, final String area ) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleViewDir); fileDirectories.add(getArea(area).toString()); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateMenuXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateMenuXml.java index d699ce927..943dd257a 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateMenuXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateMenuXml.java @@ -31,12 +31,15 @@ public FindOrCreateMenuXml(final Project project) { * @return PsiFile */ public PsiFile execute(final String actionName, final String moduleName) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); fileDirectories.add(Areas.adminhtml.toString()); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateQueueXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateQueueXml.java index 72a2d0781..b63862c8d 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateQueueXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateQueueXml.java @@ -38,6 +38,10 @@ public FindOrCreateQueueXml(final Project project) { */ public PsiFile execute(final String actionName, final String moduleName) { PsiDirectory parentDirectory = this.moduleIndex.getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateRoutesXml.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateRoutesXml.java index 385aef23a..426cd256f 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateRoutesXml.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/util/FindOrCreateRoutesXml.java @@ -32,12 +32,15 @@ public FindOrCreateRoutesXml(final Project project) { * @return PsiFile */ public PsiFile execute(final String actionName, final String moduleName, final String area) { + PsiDirectory parentDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (parentDirectory == null) { + return null; + } final DirectoryGenerator directoryGenerator = DirectoryGenerator.getInstance(); final FileFromTemplateGenerator fileFromTemplateGenerator = new FileFromTemplateGenerator(project); - - PsiDirectory parentDirectory = new ModuleIndex(project) - .getModuleDirectoryByModuleName(moduleName); final ArrayList fileDirectories = new ArrayList<>(); fileDirectories.add(Package.moduleBaseAreaDir); fileDirectories.add(getArea(area).toString()); diff --git a/src/com/magento/idea/magento2plugin/actions/generation/generator/xml/WebApiDeclarationGenerator.java b/src/com/magento/idea/magento2plugin/actions/generation/generator/xml/WebApiDeclarationGenerator.java index d80ec91bf..16d3c32e8 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/generator/xml/WebApiDeclarationGenerator.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/generator/xml/WebApiDeclarationGenerator.java @@ -75,6 +75,19 @@ public WebApiDeclarationGenerator( public PsiFile generate(final @NotNull String actionName) { final PsiDirectory moduleDirectory = new ModuleIndex(project).getModuleDirectoryByModuleName(data.getModuleName()); + + if (moduleDirectory == null) { + JOptionPane.showMessageDialog( + null, + validatorBundle.message( + "validator.file.cantBeCreated", + "Web API XML file" + ), + commonBundle.message("common.error"), + JOptionPane.ERROR_MESSAGE + ); + return null; + } final PsiDirectory fileDirectory = directoryGenerator.findOrCreateSubdirectory( moduleDirectory, diff --git a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceExtractor.java b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceExtractor.java index 6766b38cb..78f08b0e2 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceExtractor.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceExtractor.java @@ -9,6 +9,9 @@ import com.jetbrains.php.lang.psi.elements.Parameter; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpReturnType; +import com.jetbrains.php.lang.psi.elements.impl.ClassConstImpl; +import com.jetbrains.php.lang.psi.elements.impl.ClassConstantReferenceImpl; +import com.jetbrains.php.lang.psi.elements.impl.ParameterImpl; import com.jetbrains.php.lang.psi.resolve.types.PhpType; import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor; import java.util.Collection; @@ -39,6 +42,7 @@ public void visitPhpClass(final PhpClass phpClass) { @Override public void visitPhpParameter(final Parameter parameter) { PhpClassReferenceExtractor.this.processParameterReference(parameter); + PhpClassReferenceExtractor.this.processUsedForDefaultValueTypeReference(parameter); } /** @@ -77,6 +81,39 @@ public void processParameterReference(final @NotNull Parameter parameter) { this.processReference(getNameFromFqn(complexType), complexType, parameter); } + /** + * Process reference for complex type if it is exists in the default parameter value. + * + * @param parameter Parameter + */ + public void processUsedForDefaultValueTypeReference(final @NotNull Parameter parameter) { + if (!(parameter instanceof ParameterImpl)) { + return; + } + final PsiElement defaultValue = parameter.getDefaultValue(); + + if (!(defaultValue instanceof ClassConstantReferenceImpl)) { + return; + } + final PsiElement constant = ((ClassConstantReferenceImpl) defaultValue).resolve(); + + if (!(constant instanceof ClassConstImpl)) { + return; + } + final PhpClass usedTypeClass = ((ClassConstImpl) constant).getContainingClass(); + + if (usedTypeClass == null) { + return; + } + final String complexType = extractComplexType(usedTypeClass.getType()); + + if (complexType == null) { + return; + } + + this.processReference(getNameFromFqn(complexType), complexType, parameter); + } + /** * Process reference for non primitive return type. * diff --git a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceResolver.java b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceResolver.java index ed952c129..70975b599 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceResolver.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceResolver.java @@ -85,7 +85,7 @@ protected void processReference( final @NotNull PsiElement identifier ) { if (!PhpType.isPrimitiveType(name)) { - this.myCandidatesToImportStorage.processReference(name, fqn, identifier); + this.myCandidatesToImportStorage.processReference(name, fqn); } } @@ -142,22 +142,22 @@ private Map importWithConflictResolve( referencesToReplace.put(name, originalFqn); } else { final String importedFqn = aliases.get(name); - if (!PhpLangUtil.equalsClassNames(importedFqn, originalFqn)) { - if (importedFqn != null) { - final String originalName = PhpLangUtil.toShortName(originalFqn); - final String fqnForOriginalName = aliases.get(originalName); - if (fqnForOriginalName != null - && !PhpLangUtil.equalsClassNames(fqnForOriginalName, originalFqn)) { - referencesToReplace.put(name, originalFqn); - } else { - referencesToReplace.put(name, originalName); - if (fqnForOriginalName == null) { - insertUseStatement(scopeHolder, originalName, originalFqn); - } - } + + if (importedFqn != null + && !PhpLangUtil.equalsClassNames(importedFqn, originalFqn)) { + final String originalName = PhpLangUtil.toShortName(originalFqn); + final String fqnForOriginalName = aliases.get(originalName); + if (fqnForOriginalName != null + && !PhpLangUtil.equalsClassNames(fqnForOriginalName, originalFqn)) { + referencesToReplace.put(name, originalFqn); } else { - insertUseStatement(scopeHolder, name, originalFqn); + referencesToReplace.put(name, originalName); + if (fqnForOriginalName == null) { + insertUseStatement(scopeHolder, originalName, originalFqn); + } } + } else { + insertUseStatement(scopeHolder, name, originalFqn); } } } diff --git a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceStorage.java b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceStorage.java index 726988cc6..cba336224 100644 --- a/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceStorage.java +++ b/src/com/magento/idea/magento2plugin/actions/generation/references/PhpClassReferenceStorage.java @@ -5,15 +5,13 @@ package com.magento.idea.magento2plugin.actions.generation.references; -import com.intellij.psi.PsiElement; -import com.jetbrains.php.refactoring.importReferences.PhpClassReferenceExtractor; import gnu.trove.THashMap; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class PhpClassReferenceStorage extends PhpClassReferenceExtractor { +public class PhpClassReferenceStorage { private final Map myReferences = new THashMap<>(); @@ -22,12 +20,10 @@ public class PhpClassReferenceStorage extends PhpClassReferenceExtractor { * * @param name String * @param fqn String - * @param identifier PsiElement */ protected void processReference( final @NotNull String name, - final @NotNull String fqn, - final @NotNull PsiElement identifier + final @NotNull String fqn ) { this.myReferences.put(name, fqn); } diff --git a/src/com/magento/idea/magento2plugin/actions/groups/NewModuleFileGroup.java b/src/com/magento/idea/magento2plugin/actions/groups/NewModuleFileGroup.java index 8d3db82df..e97d29bf0 100644 --- a/src/com/magento/idea/magento2plugin/actions/groups/NewModuleFileGroup.java +++ b/src/com/magento/idea/magento2plugin/actions/groups/NewModuleFileGroup.java @@ -14,6 +14,7 @@ import com.intellij.psi.PsiElement; import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.actions.generation.util.IsClickedDirectoryInsideProject; +import com.magento.idea.magento2plugin.indexes.ModuleIndex; import com.magento.idea.magento2plugin.project.Settings; import com.magento.idea.magento2plugin.util.magento.GetModuleNameByDirectoryUtil; import javax.swing.Icon; @@ -45,7 +46,10 @@ public void update(final AnActionEvent event) { } final Project project = event.getData(PlatformDataKeys.PROJECT); - if (!IsClickedDirectoryInsideProject.getInstance() + + if (project == null + || !Settings.isEnabled(project) + || !IsClickedDirectoryInsideProject.getInstance() .execute(project, (PsiDirectory) psiElement)) { event.getPresentation().setVisible(false); return; @@ -53,10 +57,17 @@ public void update(final AnActionEvent event) { final String moduleName = GetModuleNameByDirectoryUtil .execute((PsiDirectory) psiElement, project); - if (Settings.isEnabled(project) && moduleName != null) { - event.getPresentation().setVisible(true); - return; + + if (moduleName != null) { + final PsiDirectory moduleDirectory = new ModuleIndex(project) + .getModuleDirectoryByModuleName(moduleName); + + if (moduleDirectory != null) { + event.getPresentation().setVisible(true); + return; + } } + event.getPresentation().setVisible(false); } } diff --git a/src/com/magento/idea/magento2plugin/indexes/ModuleIndex.java b/src/com/magento/idea/magento2plugin/indexes/ModuleIndex.java index c3facb976..e87fcbb31 100644 --- a/src/com/magento/idea/magento2plugin/indexes/ModuleIndex.java +++ b/src/com/magento/idea/magento2plugin/indexes/ModuleIndex.java @@ -5,6 +5,7 @@ package com.magento.idea.magento2plugin.indexes; +import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; @@ -23,6 +24,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.jetbrains.annotations.Nullable; public final class ModuleIndex { @@ -116,9 +118,13 @@ private List getNames( * @param moduleName String * @return PsiDirectory */ - public PsiDirectory getModuleDirectoryByModuleName(final String moduleName) { + public @Nullable PsiDirectory getModuleDirectoryByModuleName(final String moduleName) { + if (DumbService.getInstance(project).isDumb()) { + return null; + } final FileBasedIndex index = FileBasedIndex .getInstance(); + final Collection files = index.getContainingFiles( ModuleNameIndex.KEY, moduleName, @@ -126,6 +132,10 @@ public PsiDirectory getModuleDirectoryByModuleName(final String moduleName) { GlobalSearchScope.allScope(project), PhpFileType.INSTANCE )); + + if (files.isEmpty()) { + return null; + } final VirtualFile virtualFile = files.iterator().next(); return PsiManager.getInstance(project).findDirectory(virtualFile.getParent()); diff --git a/src/com/magento/idea/magento2plugin/inspections/php/ModuleDeclarationInRegistrationPhpInspection.java b/src/com/magento/idea/magento2plugin/inspections/php/ModuleDeclarationInRegistrationPhpInspection.java index f8ddfb205..004d26937 100644 --- a/src/com/magento/idea/magento2plugin/inspections/php/ModuleDeclarationInRegistrationPhpInspection.java +++ b/src/com/magento/idea/magento2plugin/inspections/php/ModuleDeclarationInRegistrationPhpInspection.java @@ -7,23 +7,28 @@ import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; +import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.inspections.PhpInspection; +import com.jetbrains.php.lang.psi.elements.Method; +import com.jetbrains.php.lang.psi.elements.MethodReference; +import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor; import com.magento.idea.magento2plugin.bundles.InspectionBundle; import com.magento.idea.magento2plugin.inspections.php.fix.PhpModuleNameQuickFix; import com.magento.idea.magento2plugin.inspections.util.GetEditableModuleNameByRootFileUtil; import com.magento.idea.magento2plugin.magento.files.RegistrationPhp; +import com.magento.idea.magento2plugin.magento.packages.code.FrameworkLibraryType; import com.magento.idea.magento2plugin.util.magento.IsFileInEditableModuleUtil; import org.jetbrains.annotations.NotNull; public class ModuleDeclarationInRegistrationPhpInspection extends PhpInspection { - @NotNull @Override - public PsiElementVisitor buildVisitor( + public @NotNull PsiElementVisitor buildVisitor( final @NotNull ProblemsHolder problemsHolder, final boolean isOnTheFly ) { @@ -33,19 +38,43 @@ public PsiElementVisitor buildVisitor( public void visitPhpStringLiteralExpression(final StringLiteralExpression expression) { final PsiFile file = expression.getContainingFile(); final String filename = file.getName(); - if (!filename.equals(RegistrationPhp.FILE_NAME)) { - return; + + if (!RegistrationPhp.FILE_NAME.equals(filename)) { + return; + } + final MethodReference callerReference = PsiTreeUtil.getParentOfType( + expression, + MethodReference.class + ); + + if (callerReference == null) { + return; + } + final PsiElement caller = callerReference.resolve(); + + if (!(caller instanceof Method)) { + return; } + final PhpClass callerOwner = ((Method) caller).getContainingClass(); + + if (callerOwner == null + || !FrameworkLibraryType.COMPONENT_REGISTRAR.getType().equals( + callerOwner.getPresentableFQN() + )) { + return; + } + if (!IsFileInEditableModuleUtil.execute(file)) { - return; + return; } final String expectedName = GetEditableModuleNameByRootFileUtil.execute(file); final String actualName = expression.getContents(); + if (actualName.equals(expectedName)) { - return; + return; } - final InspectionBundle inspectionBundle = new InspectionBundle(); + problemsHolder.registerProblem( expression, inspectionBundle.message( diff --git a/src/com/magento/idea/magento2plugin/inspections/php/PluginInspection.java b/src/com/magento/idea/magento2plugin/inspections/php/PluginInspection.java index 06f485176..c5e4dd744 100644 --- a/src/com/magento/idea/magento2plugin/inspections/php/PluginInspection.java +++ b/src/com/magento/idea/magento2plugin/inspections/php/PluginInspection.java @@ -30,14 +30,13 @@ import java.util.ArrayList; import org.jetbrains.annotations.NotNull; -@SuppressWarnings({"PMD.ExcessiveMethodLength", "PMD.NPathComplexity"}) +@SuppressWarnings({"PMD.ExcessiveMethodLength", "PMD.NPathComplexity", "PMD.CognitiveComplexity"}) public class PluginInspection extends PhpInspection { private static final String WRONG_PARAM_TYPE = "inspection.wrong_param_type"; - @NotNull @Override - public PsiElementVisitor buildVisitor( + public @NotNull PsiElementVisitor buildVisitor( final @NotNull ProblemsHolder problemsHolder, final boolean isOnTheFly ) { @@ -146,7 +145,7 @@ private void checkTargetMethod( final String targetClassMethodName, final Method targetMethod ) { - if (targetClassMethodName.equals(MagentoPhpClass.CONSTRUCT_METHOD_NAME)) { + if (MagentoPhpClass.CONSTRUCT_METHOD_NAME.equals(targetClassMethodName)) { problemsHolder.registerProblem( pluginMethod.getNameIdentifier(), inspectionBundle.message("inspection.plugin.error.constructMethod"), @@ -167,7 +166,7 @@ private void checkTargetMethod( ProblemHighlightType.ERROR ); } - if (!targetMethod.getAccess().toString().equals(AbstractPhpFile.PUBLIC_ACCESS)) { + if (!AbstractPhpFile.PUBLIC_ACCESS.equals(targetMethod.getAccess().toString())) { problemsHolder.registerProblem( pluginMethod.getNameIdentifier(), inspectionBundle.message("inspection.plugin.error.nonPublicMethod"), @@ -187,6 +186,9 @@ private void checkParametersCompatibility( int index = 0; for (final Parameter pluginMethodParameter : pluginMethodParameters) { + if (pluginMethodParameter.getName().isEmpty()) { + continue; + } index++; String declaredType = pluginMethodParameter.getDeclaredType().toString(); @@ -276,7 +278,7 @@ private void checkParametersCompatibility( if (declaredType.isEmpty()) { continue; } - if (!declaredType.equals(MagentoPhpClass.PHP_NULL)) { + if (!MagentoPhpClass.PHP_NULL.equals(declaredType)) { problemsHolder.registerProblem( pluginMethodParameter, PhpBundle.message( diff --git a/src/com/magento/idea/magento2plugin/inspections/php/util/PhpClassImplementsNoninterceptableInterfaceUtil.java b/src/com/magento/idea/magento2plugin/inspections/php/util/PhpClassImplementsNoninterceptableInterfaceUtil.java index b75099e7b..1f611196d 100644 --- a/src/com/magento/idea/magento2plugin/inspections/php/util/PhpClassImplementsNoninterceptableInterfaceUtil.java +++ b/src/com/magento/idea/magento2plugin/inspections/php/util/PhpClassImplementsNoninterceptableInterfaceUtil.java @@ -5,6 +5,7 @@ package com.magento.idea.magento2plugin.inspections.php.util; +import com.intellij.util.SlowOperations; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.magento.idea.magento2plugin.magento.files.Plugin; import org.jetbrains.annotations.NotNull; @@ -17,15 +18,20 @@ private PhpClassImplementsNoninterceptableInterfaceUtil() {} * Check whether class implements NoninterceptableInterface. * * @param phpClass PhpClass + * * @return bool */ public static boolean execute(final @NotNull PhpClass phpClass) { - final PhpClass[] interfaces = phpClass.getImplementedInterfaces(); + final PhpClass[] interfaces = SlowOperations.allowSlowOperations( + phpClass::getImplementedInterfaces + ); + if (interfaces.length == 0) { return false; } + for (final PhpClass targetInterfaceClass: interfaces) { - if (targetInterfaceClass.getFQN().equals(Plugin.NON_INTERCEPTABLE_FQN)) { + if (Plugin.NON_INTERCEPTABLE_FQN.equals(targetInterfaceClass.getFQN())) { return true; } } diff --git a/src/com/magento/idea/magento2plugin/inspections/xml/ModuleDeclarationInModuleXmlInspection.java b/src/com/magento/idea/magento2plugin/inspections/xml/ModuleDeclarationInModuleXmlInspection.java index b87e429ec..0d0ea58fb 100644 --- a/src/com/magento/idea/magento2plugin/inspections/xml/ModuleDeclarationInModuleXmlInspection.java +++ b/src/com/magento/idea/magento2plugin/inspections/xml/ModuleDeclarationInModuleXmlInspection.java @@ -28,20 +28,22 @@ public class ModuleDeclarationInModuleXmlInspection extends XmlSuppressableInspectionTool { - @NotNull @Override - public PsiElementVisitor buildVisitor( + public @NotNull PsiElementVisitor buildVisitor( final @NotNull ProblemsHolder problemsHolder, final boolean isOnTheFly ) { return new XmlElementVisitor() { + @Override public void visitXmlAttributeValue(final XmlAttributeValue value) { final PsiFile file = value.getContainingFile(); final String filename = file.getName(); - if (!filename.equals(ModuleXml.FILE_NAME)) { + + if (!ModuleXml.FILE_NAME.equals(filename)) { return; } + if (!IsFileInEditableModuleUtil.execute(file)) { return; } @@ -49,21 +51,23 @@ public void visitXmlAttributeValue(final XmlAttributeValue value) { if (isSubTag(value, (XmlFile) file)) { return; } - final PsiDirectory etcDirectory = file.getParent(); + if (etcDirectory == null) { return; } - final String attributeName = XmlAttributeValuePattern.getLocalName(value); + if (attributeName != null && attributeName.equals(ModuleXml.MODULE_ATTR_NAME)) { final String expectedName = GetEditableModuleNameByRootFileUtil.execute(etcDirectory); final String actualName = value.getValue(); - if (actualName.equals(expectedName)) { + + if (actualName.equals(expectedName) || actualName.trim().isEmpty()) { return; } final InspectionBundle inspectionBundle = new InspectionBundle(); + problemsHolder.registerProblem( value, inspectionBundle.message( @@ -81,26 +85,27 @@ public void visitXmlAttributeValue(final XmlAttributeValue value) { protected boolean isSubTag(final XmlAttributeValue value, final XmlFile file) { final XmlAttribute xmlAttribute = PsiTreeUtil.getParentOfType(value, XmlAttribute.class); + if (xmlAttribute == null) { return true; } - final XmlTag xmlTag = PsiTreeUtil.getParentOfType(xmlAttribute, XmlTag.class); + if (xmlTag == null) { return true; } - final XmlDocument xmlDocument = file.getDocument(); + if (xmlDocument == null) { return true; } - final XmlTag xmlRootTag = xmlDocument.getRootTag(); + if (xmlRootTag == null) { return true; } - final XmlTag rootTag = PsiTreeUtil.getParentOfType(xmlTag, XmlTag.class); + return rootTag == null || !(rootTag.getName().equals(xmlRootTag.getName())); } } diff --git a/src/com/magento/idea/magento2plugin/inspections/xml/PluginDeclarationInspection.java b/src/com/magento/idea/magento2plugin/inspections/xml/PluginDeclarationInspection.java index 33a325c15..a65c4d37c 100644 --- a/src/com/magento/idea/magento2plugin/inspections/xml/PluginDeclarationInspection.java +++ b/src/com/magento/idea/magento2plugin/inspections/xml/PluginDeclarationInspection.java @@ -9,6 +9,7 @@ import com.intellij.codeInspection.ProblemsHolder; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.openapi.util.Pair; +import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; @@ -118,8 +119,11 @@ public void visitFile(final PsiFile file) { pluginIndex, file ); + final XmlAttribute pluginTypeAttribute = + pluginTypeXmlTag.getAttribute(ModuleDiXml.TYPE_ATTR); if (pluginTypeDisabledAttribute != null + && pluginTypeAttribute == null && pluginTypeDisabledAttribute.getValue() != null && pluginTypeDisabledAttribute.getValue().equals("true") && !pluginTypeName.isEmpty() @@ -175,6 +179,11 @@ private List> fetchModuleNamesWhereSamePluginNameUsed( final PsiFile file ) { final List> modulesName = new ArrayList<>(); + final PsiDirectory parentDirectory = file.getContainingDirectory(); + + if (parentDirectory == null) { + return modulesName; + } final String currentFileDirectory = file.getContainingDirectory().toString(); final String currentFileFullPath = currentFileDirectory.concat(File.separator).concat(file.getName()); diff --git a/src/com/magento/idea/magento2plugin/lang/injection/UiComponentSyntaxInjector.java b/src/com/magento/idea/magento2plugin/lang/injection/UiComponentSyntaxInjector.java new file mode 100644 index 000000000..e202d6539 --- /dev/null +++ b/src/com/magento/idea/magento2plugin/lang/injection/UiComponentSyntaxInjector.java @@ -0,0 +1,82 @@ +/* + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +package com.magento.idea.magento2plugin.lang.injection; + +import com.intellij.json.JsonLanguage; +import com.intellij.lang.injection.MultiHostInjector; +import com.intellij.lang.injection.MultiHostRegistrar; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiLanguageInjectionHost; +import com.intellij.psi.html.HtmlTag; +import com.intellij.psi.templateLanguages.OuterLanguageElement; +import com.intellij.psi.xml.XmlText; +import java.util.List; +import org.jetbrains.annotations.NotNull; + +public class UiComponentSyntaxInjector implements MultiHostInjector { + + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") + @Override + public void getLanguagesToInject( + final @NotNull MultiHostRegistrar registrar, + final @NotNull PsiElement host + ) { + if (!isUiComponentTag(host)) { + return; + } + PsiElement targetXmlText = null; + + for (final PsiElement element : host.getChildren()) { + if (element instanceof XmlText) { + targetXmlText = element; + break; + } + } + + if (targetXmlText == null) { + return; + } + registrar.startInjecting(JsonLanguage.INSTANCE); + int startPosition = 0; + + for (final PsiElement element : targetXmlText.getChildren()) { + if (!(element instanceof OuterLanguageElement)) { + final int endPosition = Math.min( + startPosition + element.getTextLength(), + targetXmlText.getTextLength() + ); + + if (startPosition > element.getStartOffsetInParent()) { + startPosition = element.getStartOffsetInParent(); + } + registrar.addPlace( + null, + null, + (PsiLanguageInjectionHost) targetXmlText, + new TextRange(startPosition, endPosition) + ); + } + startPosition += element.getTextLength(); + } + registrar.doneInjecting(); + } + + @Override + public @NotNull List> elementsToInjectIn() { + return List.of(HtmlTag.class); + } + + private boolean isUiComponentTag(final @NotNull PsiElement host) { + if (!(host instanceof HtmlTag)) { + return false; + } + final HtmlTag tag = (HtmlTag) host; + final String typeAttributeValue = tag.getAttributeValue("type"); + + return typeAttributeValue != null && typeAttributeValue.equals("text/x-magento-init"); + } +} diff --git a/src/com/magento/idea/magento2plugin/lang/psi/search/AllFilesExceptTestsScope.java b/src/com/magento/idea/magento2plugin/lang/psi/search/AllFilesExceptTestsScope.java new file mode 100644 index 000000000..99e523820 --- /dev/null +++ b/src/com/magento/idea/magento2plugin/lang/psi/search/AllFilesExceptTestsScope.java @@ -0,0 +1,71 @@ +/* + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +package com.magento.idea.magento2plugin.lang.psi.search; + +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.search.GlobalSearchScope; +import com.magento.idea.magento2plugin.lang.roots.MagentoTestSourceFilter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class AllFilesExceptTestsScope extends GlobalSearchScope { + + public static final String SCOPE_NAME = "All Files Except Tests"; + private static AllFilesExceptTestsScope instance; + private final Project project; + + /** + * Get search scope instance. + * + * @param project Project + * + * @return AllFilesExceptTestsScope + */ + @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") + public static synchronized AllFilesExceptTestsScope getInstance( + final @Nullable Project project + ) { + if (instance == null) { + instance = new AllFilesExceptTestsScope(project); + } + + return instance; + } + + /** + * Magento search scope constructor. + * + * @param project Project + */ + private AllFilesExceptTestsScope(final @Nullable Project project) { + super(project); + this.project = project; + } + + @Override + public @NotNull String getDisplayName() { + return SCOPE_NAME; + } + + @Override + public boolean contains(final @NotNull VirtualFile file) { + assert project != null; + return GlobalSearchScope.allScope(project).contains(file) + && !(new MagentoTestSourceFilter().isTestSource(file, project)); + } + + @Override + public boolean isSearchInModuleContent(final @NotNull Module module) { + return true; + } + + @Override + public boolean isSearchInLibraries() { + return true; + } +} diff --git a/src/com/magento/idea/magento2plugin/lang/psi/search/MagentoSearchScopesProvider.java b/src/com/magento/idea/magento2plugin/lang/psi/search/MagentoSearchScopesProvider.java new file mode 100644 index 000000000..e1a89c659 --- /dev/null +++ b/src/com/magento/idea/magento2plugin/lang/psi/search/MagentoSearchScopesProvider.java @@ -0,0 +1,32 @@ +/* + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +package com.magento.idea.magento2plugin.lang.psi.search; + +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.NlsContexts; +import com.intellij.psi.search.SearchScope; +import com.intellij.psi.search.SearchScopeProvider; +import java.util.Collections; +import java.util.List; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MagentoSearchScopesProvider implements SearchScopeProvider { + + @Override + public @Nullable @NlsContexts.Separator String getDisplayName() { + return "Magento"; + } + + @Override + public @NotNull List getSearchScopes( + final @NotNull Project project, + final @NotNull DataContext dataContext + ) { + return Collections.singletonList(AllFilesExceptTestsScope.getInstance(project)); + } +} diff --git a/src/com/magento/idea/magento2plugin/lang/roots/MagentoTestSourceFilter.java b/src/com/magento/idea/magento2plugin/lang/roots/MagentoTestSourceFilter.java new file mode 100644 index 000000000..da99c0040 --- /dev/null +++ b/src/com/magento/idea/magento2plugin/lang/roots/MagentoTestSourceFilter.java @@ -0,0 +1,30 @@ +/* + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +package com.magento.idea.magento2plugin.lang.roots; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.TestSourcesFilter; +import com.intellij.openapi.vfs.VirtualFile; +import com.jetbrains.php.lang.PhpFileType; +import org.jetbrains.annotations.NotNull; + +public class MagentoTestSourceFilter extends TestSourcesFilter { + + private static final String TEST_CLASS_SUFFIX = "Test"; + + @Override + public boolean isTestSource(final @NotNull VirtualFile file, final @NotNull Project project) { + final String fileName = file.getNameWithoutExtension(); + final int suffixIndex = fileName.length() - TEST_CLASS_SUFFIX.length(); + + if (suffixIndex < 0) { + return false; + } + + return file.getFileType().equals(PhpFileType.INSTANCE) + && "Test".equals(fileName.substring(suffixIndex)); + } +} diff --git a/src/com/magento/idea/magento2plugin/linemarker/SearchGutterIconNavigationHandler.java b/src/com/magento/idea/magento2plugin/linemarker/SearchGutterIconNavigationHandler.java new file mode 100644 index 000000000..8f235a241 --- /dev/null +++ b/src/com/magento/idea/magento2plugin/linemarker/SearchGutterIconNavigationHandler.java @@ -0,0 +1,47 @@ +/* + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +package com.magento.idea.magento2plugin.linemarker; + +import com.intellij.codeInsight.daemon.GutterIconNavigationHandler; +import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator; +import com.intellij.ide.util.DefaultPsiElementCellRenderer; +import com.intellij.psi.NavigatablePsiElement; +import com.intellij.psi.PsiElement; +import java.awt.event.MouseEvent; +import java.util.Collection; +import org.jetbrains.annotations.NotNull; + +public class SearchGutterIconNavigationHandler + implements GutterIconNavigationHandler { + + private final Collection myReferences; + private final @NotNull String popupTitle; + + /** + * Search gutter icon navigation handler constructor. + * + * @param references Collection + * @param popupTitle String + */ + public SearchGutterIconNavigationHandler( + final Collection references, + final @NotNull String popupTitle + ) { + this.popupTitle = popupTitle; + myReferences = references; + } + + @Override + public void navigate(final MouseEvent event, final T elt) { + PsiElementListNavigator.openTargets( + event, + myReferences.toArray(NavigatablePsiElement.EMPTY_NAVIGATABLE_ELEMENT_ARRAY), + popupTitle, + "Open in Find Tool Window",// Ignored + new DefaultPsiElementCellRenderer() + ); + } +} diff --git a/src/com/magento/idea/magento2plugin/linemarker/php/GraphQlResolverUsageLineMarkerProvider.java b/src/com/magento/idea/magento2plugin/linemarker/php/GraphQlResolverUsageLineMarkerProvider.java index 3978532e7..005667324 100644 --- a/src/com/magento/idea/magento2plugin/linemarker/php/GraphQlResolverUsageLineMarkerProvider.java +++ b/src/com/magento/idea/magento2plugin/linemarker/php/GraphQlResolverUsageLineMarkerProvider.java @@ -2,50 +2,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.linemarker.php; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; -import com.intellij.lang.jsgraphql.GraphQLIcons; +import com.intellij.lang.jsgraphql.icons.GraphQLIcons; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.magento.idea.magento2plugin.project.Settings; import com.magento.idea.magento2plugin.util.magento.graphql.GraphQlUsagesCollector; import com.magento.idea.magento2plugin.util.magento.graphql.GraphQlUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Collection; import java.util.List; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class GraphQlResolverUsageLineMarkerProvider implements LineMarkerProvider { - @Nullable + @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { + public @Nullable LineMarkerInfo getLineMarkerInfo(final @NotNull PsiElement psiElement) { return null; } @Override - public void collectSlowLineMarkers(@NotNull List psiElements, @NotNull Collection> collection) { - if (psiElements.size() > 0) { - if (!Settings.isEnabled(psiElements.get(0).getProject())) { - return; - } + public void collectSlowLineMarkers( + final @NotNull List psiElements, + final @NotNull Collection> collection + ) { + if (!psiElements.isEmpty() && !Settings.isEnabled(psiElements.get(0).getProject())) { + return; } - for (PsiElement psiElement : psiElements) { + for (final PsiElement psiElement : psiElements) { if (psiElement instanceof PhpClass) { - List results; - if (!GraphQlUtil.isResolver((PhpClass) psiElement)) { return; } - GraphQlUsagesCollector collector = new GraphQlUsagesCollector(); - results = collector.getGraphQLUsages((PhpClass) psiElement); + final GraphQlUsagesCollector collector = new GraphQlUsagesCollector();//NOPMD + final List results = collector.getGraphQLUsages( + (PhpClass) psiElement + ); - if (results.size() > 0 ) { + if (!results.isEmpty()) { collection.add(NavigationGutterIconBuilder .create(GraphQLIcons.FILE) .setTargets(results) diff --git a/src/com/magento/idea/magento2plugin/linemarker/php/PluginLineMarkerProvider.java b/src/com/magento/idea/magento2plugin/linemarker/php/PluginLineMarkerProvider.java index 9b9724b8e..5d4500d65 100644 --- a/src/com/magento/idea/magento2plugin/linemarker/php/PluginLineMarkerProvider.java +++ b/src/com/magento/idea/magento2plugin/linemarker/php/PluginLineMarkerProvider.java @@ -2,12 +2,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.linemarker.php; +import com.intellij.codeInsight.daemon.GutterIconNavigationHandler; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.icons.AllIcons; +import com.intellij.psi.NavigatablePsiElement; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; @@ -15,35 +18,53 @@ import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; +import com.magento.idea.magento2plugin.linemarker.SearchGutterIconNavigationHandler; import com.magento.idea.magento2plugin.project.Settings; import com.magento.idea.magento2plugin.stubs.indexes.PluginIndex; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.commons.lang.WordUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - public class PluginLineMarkerProvider implements LineMarkerProvider { - @Nullable + + private static final String TOOLTIP_TEXT = "Navigate to plugins"; + private static final int MIN_PLUGIN_METHOD_NAME_LENGTH = 6; + @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { + public @Nullable LineMarkerInfo getLineMarkerInfo(final @NotNull PsiElement psiElement) { return null; } @Override - public void collectSlowLineMarkers(@NotNull List psiElements, @NotNull Collection> collection) { - if (psiElements.size() > 0) { - if (!Settings.isEnabled(psiElements.get(0).getProject())) { - return; - } + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") + public void collectSlowLineMarkers( + final @NotNull List psiElements, + final @NotNull Collection> collection + ) { + if (psiElements.isEmpty()) { + return; } - PluginClassCache pluginClassCache = new PluginClassCache(); - ClassPluginCollector classPluginCollector = new ClassPluginCollector(pluginClassCache); - MethodPluginCollector methodPluginCollector = new MethodPluginCollector(pluginClassCache); - for (PsiElement psiElement : psiElements) { + if (!Settings.isEnabled(psiElements.get(0).getProject())) { + return; + } + final PluginClassCache pluginClassCache = new PluginClassCache(); + final ClassPluginCollector classPluginCollector = new ClassPluginCollector( + pluginClassCache + ); + final MethodPluginCollector methodPluginCollector = new MethodPluginCollector( + pluginClassCache + ); + + for (final PsiElement psiElement : psiElements) { if (psiElement instanceof PhpClass || psiElement instanceof Method) { - List results; + final List results; if (psiElement instanceof PhpClass) { results = classPluginCollector.collect((PhpClass) psiElement); @@ -51,12 +72,22 @@ public void collectSlowLineMarkers(@NotNull List psiElemen results = methodPluginCollector.collect((Method) psiElement); } - if (results.size() > 0 ) { - collection.add(NavigationGutterIconBuilder - .create(AllIcons.Nodes.Plugin) - .setTargets(results) - .setTooltipText("Navigate to plugins") - .createLineMarkerInfo(PsiTreeUtil.getDeepestFirst(psiElement)) + if (!results.isEmpty()) { + final GutterIconNavigationHandler navigationHandler = + new SearchGutterIconNavigationHandler<>( + (Collection) results, + TOOLTIP_TEXT + ); + + collection.add( + NavigationGutterIconBuilder + .create(AllIcons.Nodes.Plugin) + .setTargets(results) + .setTooltipText(TOOLTIP_TEXT) + .createLineMarkerInfo( + PsiTreeUtil.getDeepestFirst(psiElement), + navigationHandler + ) ); } } @@ -64,109 +95,140 @@ public void collectSlowLineMarkers(@NotNull List psiElemen } private static class PluginClassCache { - private HashMap> classPluginsMap = new HashMap>(); - List getPluginsForClass(@NotNull PhpClass phpClass, @NotNull String classFQN) { - List results = new ArrayList<>(); + private final Map> classPluginsMap = new HashMap<>(); + + public List getPluginsForClass(final @NotNull PhpClass phpClass) { + final List pluginsForClass = getPluginsForClass( + phpClass, + phpClass.getPresentableFQN() + ); + for (final PhpClass parent : phpClass.getSupers()) { + if (classPluginsMap.containsKey(parent.getFQN().substring(1))) { + continue; + } + pluginsForClass.addAll(getPluginsForClass(parent)); + } + + return pluginsForClass; + } + + public List getPluginsForClass( + final @NotNull PhpClass phpClass, + final @NotNull String classFQN + ) { if (classPluginsMap.containsKey(classFQN)) { return classPluginsMap.get(classFQN); } - List> plugins = FileBasedIndex.getInstance() - .getValues(PluginIndex.KEY, classFQN, GlobalSearchScope.allScope(phpClass.getProject())); + final List> plugins = FileBasedIndex.getInstance() + .getValues( + PluginIndex.KEY, + classFQN, + GlobalSearchScope.allScope(phpClass.getProject()) + ); + final List results = new ArrayList<>(); - if (plugins.size() == 0) { + if (plugins.isEmpty()) { classPluginsMap.put(classFQN, results); + return results; } + final PhpIndex phpIndex = PhpIndex.getInstance(phpClass.getProject()); - PhpIndex phpIndex = PhpIndex.getInstance(phpClass.getProject()); - - for (Set pluginClassNames: plugins) { - for (String pluginClassName: pluginClassNames) { + for (final Set pluginClassNames : plugins) { + for (final String pluginClassName: pluginClassNames) { results.addAll(phpIndex.getClassesByFQN(pluginClassName)); } } classPluginsMap.put(classFQN, results); + return results; } - List getPluginsForClass(@NotNull PhpClass phpClass) - { - List pluginsForClass = getPluginsForClass(phpClass, phpClass.getPresentableFQN()); - for (PhpClass parent: phpClass.getSupers()) { - pluginsForClass.addAll(getPluginsForClass(parent)); + public List getPluginMethods(final List plugins) { + final List methodList = new ArrayList<>(); + + for (final PhpClass plugin: plugins) { + methodList.addAll(getPluginMethods(plugin)); } - return pluginsForClass; + return methodList; } - List getPluginMethods(@NotNull PhpClass plugin) { - List methodList = new ArrayList(); - for (Method method : plugin.getMethods()) { + public List getPluginMethods(final @NotNull PhpClass pluginClass) { + final List methodList = new ArrayList<>(); + + for (final Method method : pluginClass.getMethods()) { if (method.getAccess().isPublic()) { - String pluginMethodName = method.getName(); - if (pluginMethodName.length() > 6) { + final String pluginMethodName = method.getName(); + + if (pluginMethodName.length() > MIN_PLUGIN_METHOD_NAME_LENGTH) { methodList.add(method); } } } - return methodList; - } - List getPluginMethods(List plugins) { - List methodList = new ArrayList(); - for (PhpClass plugin: plugins) { - methodList.addAll(getPluginMethods(plugin)); - } return methodList; } } private static class ClassPluginCollector implements Collector { - private PluginLineMarkerProvider.PluginClassCache pluginClassCache; - ClassPluginCollector(PluginLineMarkerProvider.PluginClassCache pluginClassCache) { + private final PluginLineMarkerProvider.PluginClassCache pluginClassCache; + + public ClassPluginCollector( + final PluginLineMarkerProvider.PluginClassCache pluginClassCache + ) { this.pluginClassCache = pluginClassCache; } @Override - public List collect(@NotNull PhpClass psiElement) { + public List collect(final @NotNull PhpClass psiElement) { return pluginClassCache.getPluginsForClass(psiElement); } } private static class MethodPluginCollector implements Collector { - private PluginLineMarkerProvider.PluginClassCache pluginClassCache; - MethodPluginCollector(PluginLineMarkerProvider.PluginClassCache pluginClassCache) { + private final PluginLineMarkerProvider.PluginClassCache pluginClassCache; + + public MethodPluginCollector( + final PluginLineMarkerProvider.PluginClassCache pluginClassCache + ) { this.pluginClassCache = pluginClassCache; } @Override - public List collect(@NotNull Method psiElement) { - List results = new ArrayList<>(); + public List collect(final @NotNull Method psiElement) { + final List results = new ArrayList<>(); + + final PhpClass methodClass = psiElement.getContainingClass(); - PhpClass methodClass = psiElement.getContainingClass(); if (methodClass == null) { return results; } + final List pluginsList = pluginClassCache.getPluginsForClass(methodClass); + final List pluginMethods = pluginClassCache.getPluginMethods(pluginsList); - List pluginsList = pluginClassCache.getPluginsForClass(methodClass); - List pluginMethods = pluginClassCache.getPluginMethods(pluginsList); + final String classMethodName = WordUtils.capitalize(psiElement.getName()); - String classMethodName = WordUtils.capitalize(psiElement.getName()); - for (Method pluginMethod: pluginMethods) { + for (final Method pluginMethod: pluginMethods) { if (isPluginMethodName(pluginMethod.getName(), classMethodName)) { results.add(pluginMethod); } } + return results; } - private boolean isPluginMethodName(String pluginMethodName, String classMethodName) { - return pluginMethodName.substring(5).equals(classMethodName) || pluginMethodName.substring(6).equals(classMethodName); + private boolean isPluginMethodName( + final String pluginMethodName, + final String classMethodName + ) { + return pluginMethodName.substring(5).equals(classMethodName) + || pluginMethodName.substring(6).equals(classMethodName); } } diff --git a/src/com/magento/idea/magento2plugin/linemarker/php/PluginTargetLineMarkerProvider.java b/src/com/magento/idea/magento2plugin/linemarker/php/PluginTargetLineMarkerProvider.java index b4de80de2..5f63c8620 100644 --- a/src/com/magento/idea/magento2plugin/linemarker/php/PluginTargetLineMarkerProvider.java +++ b/src/com/magento/idea/magento2plugin/linemarker/php/PluginTargetLineMarkerProvider.java @@ -21,13 +21,17 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class PluginTargetLineMarkerProvider implements LineMarkerProvider { - @Nullable + + private static final String TARGET_CLASS_TOOLTIP_TEXT = "Navigate to target class"; + private static final String TARGET_METHOD_TOOLTIP_TEXT = "Navigate to target method"; + @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull final PsiElement psiElement) { + public @Nullable LineMarkerInfo getLineMarkerInfo(final @NotNull PsiElement psiElement) { return null; } @@ -36,48 +40,52 @@ public void collectSlowLineMarkers( final @NotNull List psiElements, final @NotNull Collection> collection ) { - if (!psiElements.isEmpty() && !Settings.isEnabled(psiElements.get(0).getProject())) { + if (psiElements.isEmpty()) { + return; + } + + if (!Settings.isEnabled(psiElements.get(0).getProject())) { return; } final PluginClassCache pluginClassCache = new PluginClassCache(); - final TargetClassesCollector targetClassesCollector = - new TargetClassesCollector(pluginClassCache); - final TargetMethodsCollector targetMethodsCollector = - new TargetMethodsCollector(pluginClassCache); + final TargetClassesCollector targetClassesCollector = new TargetClassesCollector( + pluginClassCache + ); + final TargetMethodsCollector targetMethodsCollector = new TargetMethodsCollector( + pluginClassCache + ); for (final PsiElement psiElement : psiElements) { - if (psiElement instanceof PhpClass || psiElement instanceof Method) { - List results; - - if (psiElement instanceof PhpClass) { - results = targetClassesCollector.collect((PhpClass) psiElement); - if (!results.isEmpty()) { - collection.add(NavigationGutterIconBuilder - .create(AllIcons.Nodes.Class) - .setTargets(results) - .setTooltipText("Navigate to target class") - .createLineMarkerInfo(PsiTreeUtil.getDeepestFirst(psiElement)) - ); - } - } else { - results = targetMethodsCollector.collect((Method) psiElement); - if (!results.isEmpty()) { - collection.add(NavigationGutterIconBuilder - .create(AllIcons.Nodes.Method) - .setTargets(results) - .setTooltipText("Navigate to target method") - .createLineMarkerInfo(PsiTreeUtil.getDeepestFirst(psiElement)) - ); - } + if (psiElement instanceof PhpClass) { + final List results = + targetClassesCollector.collect((PhpClass) psiElement); + + if (!results.isEmpty()) { + collection.add(NavigationGutterIconBuilder + .create(AllIcons.Nodes.Class) + .setTargets(results) + .setTooltipText(TARGET_CLASS_TOOLTIP_TEXT) + .createLineMarkerInfo(PsiTreeUtil.getDeepestFirst(psiElement)) + ); + } + } else if (psiElement instanceof Method) { + final List results = + targetMethodsCollector.collect((Method) psiElement); + + if (!results.isEmpty()) { + collection.add(NavigationGutterIconBuilder + .create(AllIcons.Nodes.Method) + .setTargets(results) + .setTooltipText(TARGET_METHOD_TOOLTIP_TEXT) + .createLineMarkerInfo(PsiTreeUtil.getDeepestFirst(psiElement)) + ); } - } } } private static class PluginClassCache { - private final HashMap> pluginClassesMap = // NOPMD - new HashMap<>(); + private final Map> pluginClassesMap = new HashMap<>(); private List getTargetClassesForPlugin( @NotNull final PhpClass phpClass, @@ -119,6 +127,9 @@ protected List getTargetClassesForPlugin(@NotNull final PhpClass phpCl phpClass, phpClass.getPresentableFQN() ); for (final PhpClass parent: phpClass.getSupers()) { + if (pluginClassesMap.containsKey(parent.getFQN().substring(1))) { + continue; + } classesForPlugin.addAll(getTargetClassesForPlugin(parent)); } @@ -127,9 +138,10 @@ protected List getTargetClassesForPlugin(@NotNull final PhpClass phpCl } private static class TargetClassesCollector implements Collector { + private final PluginTargetLineMarkerProvider.PluginClassCache pluginClassCache; - TargetClassesCollector(// NOPMD + public TargetClassesCollector( final PluginTargetLineMarkerProvider.PluginClassCache pluginClassCache ) { this.pluginClassCache = pluginClassCache; @@ -142,9 +154,10 @@ public List collect(@NotNull final PhpClass psiElement) { } private static class TargetMethodsCollector implements Collector { + private final PluginTargetLineMarkerProvider.PluginClassCache pluginClassCache; - TargetMethodsCollector(// NOPMD + public TargetMethodsCollector( final PluginTargetLineMarkerProvider.PluginClassCache pluginClassCache ) { this.pluginClassCache = pluginClassCache; @@ -158,32 +171,33 @@ public List collect(@NotNull final Method pluginMethod) { if (null == getPluginPrefix(pluginMethod)) { return results; } - final PhpClass pluginClass = pluginMethod.getContainingClass(); + if (pluginClass == null) { return results; } final List targetClasses = pluginClassCache.getTargetClassesForPlugin(pluginClass); + if (targetClasses.isEmpty()) { return results; } - for (final PhpClass targetClass: targetClasses) { + for (final PhpClass targetClass : targetClasses) { final String pluginPrefix = getPluginPrefix(pluginMethod); final String targetClassMethodName = getTargetMethodName( pluginMethod, pluginPrefix ); + if (targetClassMethodName == null) { continue; } - final Method targetMethod = targetClass.findMethodByName(targetClassMethodName); + if (targetMethod == null) { continue; } - results.add(targetMethod); } @@ -192,25 +206,31 @@ public List collect(@NotNull final Method pluginMethod) { private String getTargetMethodName(final Method pluginMethod, final String pluginPrefix) { final String targetClassMethodName = pluginMethod.getName().replace(pluginPrefix, ""); + if (targetClassMethodName.isEmpty()) { return null; } final char firstCharOfTargetName = targetClassMethodName.charAt(0); + if (Character.getType(firstCharOfTargetName) == Character.LOWERCASE_LETTER) { return null; } + return Character.toLowerCase(firstCharOfTargetName) + targetClassMethodName.substring(1); } private String getPluginPrefix(final Method pluginMethod) { final String pluginMethodName = pluginMethod.getName(); + if (pluginMethodName.startsWith(Plugin.PluginType.around.toString())) { return Plugin.PluginType.around.toString(); } + if (pluginMethodName.startsWith(Plugin.PluginType.before.toString())) { return Plugin.PluginType.before.toString(); } + if (pluginMethodName.startsWith(Plugin.PluginType.after.toString())) { return Plugin.PluginType.after.toString(); } diff --git a/src/com/magento/idea/magento2plugin/linemarker/php/WebApiLineMarkerProvider.java b/src/com/magento/idea/magento2plugin/linemarker/php/WebApiLineMarkerProvider.java index b4d2f012e..ff6654430 100644 --- a/src/com/magento/idea/magento2plugin/linemarker/php/WebApiLineMarkerProvider.java +++ b/src/com/magento/idea/magento2plugin/linemarker/php/WebApiLineMarkerProvider.java @@ -1,7 +1,8 @@ -/** +/* * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.linemarker.php; import com.intellij.codeInsight.daemon.LineMarkerInfo; @@ -9,17 +10,21 @@ import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlTag; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.magento.idea.magento2plugin.MagentoIcons; import com.magento.idea.magento2plugin.project.Settings; import com.magento.idea.magento2plugin.stubs.indexes.WebApiTypeIndex; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - /** * Line marker for methods and classes which are exposed as web APIs. *

@@ -28,38 +33,47 @@ */ public class WebApiLineMarkerProvider implements LineMarkerProvider { - @Nullable @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { + public @Nullable LineMarkerInfo getLineMarkerInfo(final @NotNull PsiElement psiElement) { return null; } + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @Override - public void collectSlowLineMarkers(@NotNull List psiElements, @NotNull Collection> collection) { - if (psiElements.size() > 0) { - if (!Settings.isEnabled(psiElements.get(0).getProject())) { - return; - } + public void collectSlowLineMarkers( + final @NotNull List psiElements, + final @NotNull Collection> collection + ) { + if (psiElements.isEmpty()) { + return; + } + + if (!Settings.isEnabled(psiElements.get(0).getProject())) { + return; } - for (PsiElement psiElement: psiElements) { - WebApiRoutesCollector collector = new WebApiRoutesCollector(); + final WebApiRoutesCollector collector = new WebApiRoutesCollector(); + + for (final PsiElement psiElement : psiElements) { List results = new ArrayList<>(); + if (psiElement instanceof Method) { results = collector.getRoutes((Method) psiElement); } else if (psiElement instanceof PhpClass) { results = collector.getRoutes((PhpClass) psiElement); } - if (!(results.size() > 0)) { + if (results.isEmpty()) { continue; } - StringBuilder tooltipText = new StringBuilder("Navigate to Web API configuration:

");
-            for (XmlTag routeTag : results) {
-                tooltipText.append(routeTag.getName()).append("\n");
+            final StringBuilder tooltipText = new StringBuilder(
+                    "Navigate to Web API configuration:
"
+            );
+            for (final XmlTag routeTag : results) {
+                tooltipText.append(routeTag.getName()).append('\n');
             }
             tooltipText.append("
"); - NavigationGutterIconBuilder builder = NavigationGutterIconBuilder + final NavigationGutterIconBuilder builder = NavigationGutterIconBuilder .create(MagentoIcons.WEB_API) .setTargets(results) .setTooltipText(tooltipText.toString()); @@ -72,24 +86,28 @@ public void collectSlowLineMarkers(@NotNull List psiElemen */ private static class WebApiRoutesCollector { - private HashMap> routesCache = new HashMap<>(); + private final Map> routesCache = new HashMap<>(); + private final Map httpMethodsSortOrder; - private static final Map HTTP_METHODS_SORT_ORDER = new HashMap() {{ - put("GET", 1); - put("PUT", 2); - put("POS", 3); - put("DEL", 4); - }}; + public WebApiRoutesCollector() { + httpMethodsSortOrder = new HashMap<>(); + httpMethodsSortOrder.put("GET", 1); + httpMethodsSortOrder.put("PUT", 2); + httpMethodsSortOrder.put("POS", 3); + httpMethodsSortOrder.put("DEL", 4); + } /** * Get sorted list of Web API routes related to the specified class. */ - List getRoutes(@NotNull PhpClass phpClass) { - List routesForClass = new ArrayList<>(); - for (Method method : phpClass.getMethods()) { + public List getRoutes(final @NotNull PhpClass phpClass) { + final List routesForClass = new ArrayList<>(); + + for (final Method method : phpClass.getMethods()) { routesForClass.addAll(getRoutes(method)); } sortRoutes(routesForClass); + return routesForClass; } @@ -98,13 +116,15 @@ List getRoutes(@NotNull PhpClass phpClass) { *

* Results are cached. */ - List getRoutes(@NotNull Method method) { - String methodFqn = method.getFQN(); + public List getRoutes(final @NotNull Method method) { + final String methodFqn = method.getFQN(); + if (!routesCache.containsKey(methodFqn)) { - List routesForMethod = extractRoutesForMethod(method); + final List routesForMethod = extractRoutesForMethod(method); sortRoutes(routesForMethod); routesCache.put(methodFqn, routesForMethod); } + return routesCache.get(methodFqn); } @@ -114,38 +134,100 @@ List getRoutes(@NotNull Method method) { * Web API declarations for parent classes are taken into account. * Results are not cached. */ - List extractRoutesForMethod(@NotNull Method method) { - List routesForMethod = WebApiTypeIndex.getWebApiRoutes(method); - PhpClass phpClass = method.getContainingClass(); + public List extractRoutesForMethod(final @NotNull Method method) { + final List routesForMethod = new ArrayList<>(); + final Map> routesForMethodMap = new HashMap<>(); + + for (final Map.Entry> entry + : extractRoutesForMethodRecursively(method, routesForMethodMap).entrySet()) { + routesForMethod.addAll(entry.getValue()); + } + + return routesForMethod; + } + + private Map> extractRoutesForMethodRecursively( + final @NotNull Method method, + final Map> routesForMethod + ) { + routesForMethod.put(method.getFQN(), WebApiTypeIndex.getWebApiRoutes(method)); + final PhpClass phpClass = method.getContainingClass(); + if (phpClass == null) { return routesForMethod; } - for (PhpClass parent : method.getContainingClass().getSupers()) { - for (Method parentMethod : parent.getMethods()) { + + for (final PhpClass parent : method.getContainingClass().getSupers()) { + for (final Method parentMethod : parent.getMethods()) { if (parentMethod.getName().equals(method.getName())) { - routesForMethod.addAll(extractRoutesForMethod(parentMethod)); + if (routesForMethod.containsKey(parentMethod.getFQN())) { + continue; + } + routesForMethod.putAll( + extractRoutesForMethodRecursively( + parentMethod, + routesForMethod + ) + ); } } } + return routesForMethod; } /** * Make sure that routes are sorted as follows: GET, PUT, POST, DELETE. Then by path. */ - private void sortRoutes(List routes) { + private void sortRoutes(final List routes) { routes.sort( - (firstTag, secondTag) -> { - String substring = firstTag.getName().substring(2, 5); - Integer firstSortOrder = HTTP_METHODS_SORT_ORDER.get(substring); - Integer secondSortOrder = HTTP_METHODS_SORT_ORDER.get(secondTag.getName().substring(2, 5)); - if (firstSortOrder.compareTo(secondSortOrder) == 0) { - // Sort by route if HTTP methods are equal - return firstTag.getName().compareTo(secondTag.getName()); + (tag1, tag2) -> { + final String firstUrl = GetTagAttributeValueUtil.getValue(tag1, "url"); + final String secondUrl = GetTagAttributeValueUtil.getValue(tag2, "url"); + final String method1 = GetTagAttributeValueUtil.getValue(tag1, "method"); + final String method2 = GetTagAttributeValueUtil.getValue(tag2, "method"); + + if (method1.isEmpty() || method2.isEmpty()) { + return firstUrl.compareTo(secondUrl); + } + + if (!httpMethodsSortOrder.containsKey(method1) + || !httpMethodsSortOrder.containsKey(method2)) { + return firstUrl.compareTo(secondUrl); + } + final Integer firstSortOrder = httpMethodsSortOrder.get(method1); + final Integer secondSortOrder = httpMethodsSortOrder.get(method2); + + if (firstSortOrder.compareTo(secondSortOrder) == 0) { + // Sort by route if HTTP methods are equal + return firstUrl.compareTo(secondUrl); + } + + return firstSortOrder.compareTo(secondSortOrder); } - return firstSortOrder.compareTo(secondSortOrder); - } ); } } + + @SuppressWarnings("PMD.UseUtilityClass") + private static class GetTagAttributeValueUtil { + + public static @NotNull String getValue( + final XmlTag tag, + final @NotNull String attributeName + ) { + final XmlAttribute attribute = tag.getAttribute(attributeName); + + if (attribute == null) { + return ""; + } + final String value = attribute.getValue(); + + if (value == null) { + return ""; + } + + return value.trim(); + } + } } diff --git a/src/com/magento/idea/magento2plugin/linemarker/xml/LineMarkerXmlTagDecorator.java b/src/com/magento/idea/magento2plugin/linemarker/xml/LineMarkerXmlTagDecorator.java index 2140c601a..d4857c7c2 100644 --- a/src/com/magento/idea/magento2plugin/linemarker/xml/LineMarkerXmlTagDecorator.java +++ b/src/com/magento/idea/magento2plugin/linemarker/xml/LineMarkerXmlTagDecorator.java @@ -1,7 +1,8 @@ -/** +/* * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.linemarker.xml; import com.intellij.lang.ASTNode; @@ -10,7 +11,14 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiElementVisitor; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiInvalidElementAccessException; +import com.intellij.psi.PsiManager; +import com.intellij.psi.PsiReference; +import com.intellij.psi.ResolveState; +import com.intellij.psi.impl.source.xml.XmlTagImpl; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; @@ -25,47 +33,60 @@ import com.intellij.xml.XmlNSDescriptor; import com.magento.idea.magento2plugin.magento.packages.MagentoComponentManager; import com.magento.idea.magento2plugin.magento.packages.MagentoModule; +import java.util.Map; +import javax.swing.Icon; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.swing.*; -import java.util.Map; - /** - * Decorator for XmlTag, which allows to render user-friendly line markers. + * Decorator for XmlTag, which allows user-friendly line markers rendering. */ -abstract public class LineMarkerXmlTagDecorator implements XmlTag { +@SuppressWarnings({ + "PMD.TooManyFields", + "PMD.ExcessiveImports", + "PMD.CouplingBetweenObjects", + "PMD.ExcessivePublicCount", + "PMD.CyclomaticComplexity", + "PMD.TooManyMethods", + "PMD.AvoidUncheckedExceptionsInSignatures" +}) +public abstract class LineMarkerXmlTagDecorator implements XmlTag { protected XmlTag xmlTag; protected Project project; - public LineMarkerXmlTagDecorator(XmlTag xmlTag) { + public LineMarkerXmlTagDecorator(final XmlTag xmlTag) { this.xmlTag = xmlTag; this.project = xmlTag.getProject(); } @NotNull protected String getAreaName() { - VirtualFile containingDirectory = xmlTag.getContainingFile().getVirtualFile().getParent(); - String configDirectory = containingDirectory.getName(); + final VirtualFile containingDirectory = xmlTag + .getContainingFile().getVirtualFile().getParent(); + final String configDirectory = containingDirectory.getName(); + + if ("etc".equals(configDirectory)) { + final VirtualFile moduleDirectory = containingDirectory.getParent(); - if (configDirectory.equals("etc")) { - VirtualFile moduleDirectory = containingDirectory.getParent(); - if (moduleDirectory.getName().equals("app")) { + if ("app".equals(moduleDirectory.getName())) { return "primary"; } return "global"; } + return configDirectory; } @NotNull private String getComponentName() { - MagentoComponentManager moduleManager = MagentoComponentManager.getInstance(project); - MagentoModule module = moduleManager.getComponentOfTypeForFile(xmlTag.getContainingFile(), MagentoModule.class); + final MagentoComponentManager moduleManager = MagentoComponentManager.getInstance(project); + final MagentoModule module = moduleManager.getComponentOfTypeForFile( + xmlTag.getContainingFile(), MagentoModule.class + ); if (module == null) { return ""; @@ -75,10 +96,11 @@ private String getComponentName() { } @NotNull - abstract public String getDescription(); + public abstract String getDescription(); /** - * Get line marker text. This method should be overridden to generate user-friendly XmlTag presentation. + * Get line marker text. + * This method should be overridden to generate user-friendly XmlTag presentation. */ @Override @NotNull @@ -114,91 +136,99 @@ public XmlAttribute[] getAttributes() { } @Override - @Nullable - public XmlAttribute getAttribute(@NonNls String s, @NonNls String s1) { - return xmlTag.getAttribute(s, s1); + public @Nullable XmlAttribute getAttribute( + final @NonNls String name, + final @NonNls String namespace + ) { + return xmlTag.getAttribute(name, namespace); } @Override - @Nullable - public XmlAttribute getAttribute(@NonNls String s) { - return xmlTag.getAttribute(s); + public @Nullable XmlAttribute getAttribute(final @NonNls String qname) { + return xmlTag.getAttribute(qname); } @Override - @Nullable - public String getAttributeValue(@NonNls String s, @NonNls String s1) { - return xmlTag.getAttributeValue(s, s1); + public @Nullable String getAttributeValue( + final @NonNls String name, + final @NonNls String namespace + ) { + return xmlTag.getAttributeValue(name, namespace); } @Override - @Nullable - public String getAttributeValue(@NonNls String s) { - return xmlTag.getAttributeValue(s); + public @Nullable String getAttributeValue(final @NonNls String qname) { + return xmlTag.getAttributeValue(qname); } @Override - public XmlAttribute setAttribute(@NonNls String s, @NonNls String s1, @NonNls String s2) throws IncorrectOperationException { - return xmlTag.setAttribute(s, s1, s2); + public XmlAttribute setAttribute( + final @NonNls String name, + final @NonNls String namespace, + final @NonNls String value + ) throws IncorrectOperationException { + return xmlTag.setAttribute(name, namespace, value); } @Override - public XmlAttribute setAttribute(@NonNls String s, @NonNls String s1) throws IncorrectOperationException { - return xmlTag.setAttribute(s, s1); + public XmlAttribute setAttribute( + final @NonNls String qname, + final @NonNls String value + ) throws IncorrectOperationException { + return xmlTag.setAttribute(qname, value); } @Override - public XmlTag createChildTag(@NonNls String s, @NonNls String s1, @Nullable @NonNls String s2, boolean b) { - return xmlTag.createChildTag(s, s1, s2, b); + public XmlTag createChildTag( + final @NonNls String localName, + final @NonNls String namespace, + final @Nullable @NonNls String bodyText, + final boolean enforceNamespacesDeep + ) { + return xmlTag.createChildTag(localName, namespace, bodyText, enforceNamespacesDeep); } @Override - public XmlTag addSubTag(XmlTag xmlTag, boolean b) { - return this.xmlTag.addSubTag(xmlTag, b); + public XmlTag addSubTag(final XmlTag subTag, final boolean first) { + return this.xmlTag.addSubTag(subTag, first); } @Override - @NotNull - public XmlTag[] getSubTags() { + public @NotNull XmlTag[] getSubTags() { return xmlTag.getSubTags(); } @Override - @NotNull - public XmlTag[] findSubTags(@NonNls String s) { - return xmlTag.findSubTags(s); + public @NotNull XmlTag[] findSubTags(final @NonNls String qname) { + return xmlTag.findSubTags(qname); } @Override - @NotNull - public XmlTag[] findSubTags(@NonNls String s, @Nullable String s1) { - return xmlTag.findSubTags(s, s1); + public @NotNull XmlTag[] findSubTags( + final @NonNls String localName, + final @Nullable String namespace + ) { + return xmlTag.findSubTags(localName, namespace); } @Override - @Nullable - public XmlTag findFirstSubTag(@NonNls String s) { - return xmlTag.findFirstSubTag(s); + public @Nullable XmlTag findFirstSubTag(final @NonNls String qname) { + return xmlTag.findFirstSubTag(qname); } @Override - @NotNull - @NonNls - public String getNamespacePrefix() { + public @NotNull @NonNls String getNamespacePrefix() { return xmlTag.getNamespacePrefix(); } @Override - @NotNull - @NonNls - public String getNamespaceByPrefix(@NonNls String s) { - return xmlTag.getNamespaceByPrefix(s); + public @NotNull @NonNls String getNamespaceByPrefix(final @NonNls String prefix) { + return xmlTag.getNamespaceByPrefix(prefix); } @Override - @Nullable - public String getPrefixByNamespace(@NonNls String s) { - return xmlTag.getPrefixByNamespace(s); + public @Nullable String getPrefixByNamespace(final @NonNls String namespace) { + return xmlTag.getPrefixByNamespace(namespace); } @Override @@ -224,9 +254,11 @@ public XmlTagValue getValue() { } @Override - @Nullable - public XmlNSDescriptor getNSDescriptor(@NonNls String s, boolean b) { - return xmlTag.getNSDescriptor(s, b); + public @Nullable XmlNSDescriptor getNSDescriptor( + final @NonNls String namespace, + final boolean strict + ) { + return xmlTag.getNSDescriptor(namespace, strict); } @Override @@ -240,215 +272,163 @@ public void collapseIfEmpty() { } @Override - @Nullable - @NonNls - public String getSubTagText(@NonNls String s) { - return xmlTag.getSubTagText(s); + public @Nullable @NonNls String getSubTagText(final @NonNls String qname) { + return xmlTag.getSubTagText(qname); } @Override - public boolean processElements(PsiElementProcessor psiElementProcessor, PsiElement psiElement) { + public boolean processElements( + final PsiElementProcessor psiElementProcessor, + final PsiElement psiElement + ) { return xmlTag.processElements(psiElementProcessor, psiElement); } @Override - @NotNull - @Contract( - pure = true - ) - public Project getProject() throws PsiInvalidElementAccessException { + @Contract(pure = true) + public @NotNull Project getProject() throws PsiInvalidElementAccessException { return xmlTag.getProject(); } @Override - @NotNull - @Contract( - pure = true - ) - public Language getLanguage() { + @Contract(pure = true) + public @NotNull Language getLanguage() { return xmlTag.getLanguage(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiManager getManager() { return xmlTag.getManager(); } @Override - @NotNull - @Contract( - pure = true - ) - public PsiElement[] getChildren() { + @Contract(pure = true) + public @NotNull PsiElement[] getChildren() { return xmlTag.getChildren(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getParent() { return xmlTag.getParent(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getFirstChild() { return xmlTag.getFirstChild(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getLastChild() { return xmlTag.getLastChild(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getNextSibling() { return xmlTag.getNextSibling(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getPrevSibling() { return xmlTag.getPrevSibling(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiFile getContainingFile() throws PsiInvalidElementAccessException { return xmlTag.getContainingFile(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public TextRange getTextRange() { return xmlTag.getTextRange(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public int getStartOffsetInParent() { return xmlTag.getStartOffsetInParent(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public int getTextLength() { return xmlTag.getTextLength(); } @Override - @Nullable - @Contract( - pure = true - ) - public PsiElement findElementAt(int i) { - return xmlTag.findElementAt(i); + @Contract(pure = true) + public @Nullable PsiElement findElementAt(final int offset) { + return xmlTag.findElementAt(offset); } @Override - @Nullable - @Contract( - pure = true - ) - public PsiReference findReferenceAt(int i) { - return xmlTag.findReferenceAt(i); + @Contract(pure = true) + public @Nullable PsiReference findReferenceAt(final int offset) { + return xmlTag.findReferenceAt(offset); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public int getTextOffset() { return xmlTag.getTextOffset(); } @Override - @NonNls - @Contract( - pure = true - ) - public String getText() { + @Contract(pure = true) + public @NonNls String getText() { return xmlTag.getText(); } @Override - @NotNull - @Contract( - pure = true - ) - public char[] textToCharArray() { + @Contract(pure = true) + public @NotNull char[] textToCharArray() { return xmlTag.textToCharArray(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getNavigationElement() { return xmlTag.getNavigationElement(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public PsiElement getOriginalElement() { return xmlTag.getOriginalElement(); } @Override - @Contract( - pure = true - ) - public boolean textMatches(@NotNull @NonNls CharSequence charSequence) { + @Contract(pure = true) + public boolean textMatches(final @NotNull @NonNls CharSequence charSequence) { return xmlTag.textMatches(charSequence); } @Override - @Contract( - pure = true - ) - public boolean textMatches(@NotNull PsiElement psiElement) { + @Contract(pure = true) + public boolean textMatches(final @NotNull PsiElement psiElement) { return xmlTag.textMatches(psiElement); } @Override - @Contract( - pure = true - ) - public boolean textContains(char c) { - return xmlTag.textContains(c); + @Contract(pure = true) + public boolean textContains(final char character) { + return xmlTag.textContains(character); } @Override - public void accept(@NotNull PsiElementVisitor psiElementVisitor) { + public void accept(final @NotNull PsiElementVisitor psiElementVisitor) { xmlTag.accept(psiElementVisitor); } @Override - public void acceptChildren(@NotNull PsiElementVisitor psiElementVisitor) { + public void acceptChildren(final @NotNull PsiElementVisitor psiElementVisitor) { xmlTag.acceptChildren(psiElementVisitor); } @@ -458,37 +438,59 @@ public PsiElement copy() { } @Override - public PsiElement add(@NotNull PsiElement psiElement) throws IncorrectOperationException { + public PsiElement add( + final @NotNull PsiElement psiElement + ) throws IncorrectOperationException { return xmlTag.add(psiElement); } @Override - public PsiElement addBefore(@NotNull PsiElement psiElement, @Nullable PsiElement psiElement1) throws IncorrectOperationException { + public PsiElement addBefore( + final @NotNull PsiElement psiElement, + final @Nullable PsiElement psiElement1 + ) throws IncorrectOperationException { return xmlTag.addBefore(psiElement, psiElement1); } @Override - public PsiElement addAfter(@NotNull PsiElement psiElement, @Nullable PsiElement psiElement1) throws IncorrectOperationException { + public PsiElement addAfter( + final @NotNull PsiElement psiElement, + final @Nullable PsiElement psiElement1 + ) throws IncorrectOperationException { return xmlTag.addAfter(psiElement, psiElement1); } @Override - public void checkAdd(@NotNull PsiElement psiElement) throws IncorrectOperationException { - xmlTag.checkAdd(psiElement); + public void checkAdd(final @NotNull PsiElement psiElement) throws IncorrectOperationException { + if (xmlTag instanceof XmlTagImpl) { + ((XmlTagImpl) xmlTag).checkAdd(psiElement); + } + throw new IncorrectOperationException(getClass().getName()); } @Override - public PsiElement addRange(PsiElement psiElement, PsiElement psiElement1) throws IncorrectOperationException { + public PsiElement addRange( + final PsiElement psiElement, + final PsiElement psiElement1 + ) throws IncorrectOperationException { return xmlTag.addRange(psiElement, psiElement1); } @Override - public PsiElement addRangeBefore(@NotNull PsiElement psiElement, @NotNull PsiElement psiElement1, PsiElement psiElement2) throws IncorrectOperationException { + public PsiElement addRangeBefore( + final @NotNull PsiElement psiElement, + final @NotNull PsiElement psiElement1, + final PsiElement psiElement2 + ) throws IncorrectOperationException { return xmlTag.addRangeBefore(psiElement, psiElement1, psiElement2); } @Override - public PsiElement addRangeAfter(PsiElement psiElement, PsiElement psiElement1, PsiElement psiElement2) throws IncorrectOperationException { + public PsiElement addRangeAfter( + final PsiElement psiElement, + final PsiElement psiElement1, + final PsiElement psiElement2 + ) throws IncorrectOperationException { return xmlTag.addRangeAfter(psiElement, psiElement1, psiElement2); } @@ -499,174 +501,153 @@ public void delete() throws IncorrectOperationException { @Override public void checkDelete() throws IncorrectOperationException { - xmlTag.checkDelete(); + if (xmlTag instanceof XmlTagImpl) { + ((XmlTagImpl) xmlTag).checkDelete(); + } + throw new IncorrectOperationException(getClass().getName()); } @Override - public void deleteChildRange(PsiElement psiElement, PsiElement psiElement1) throws IncorrectOperationException { + public void deleteChildRange( + final PsiElement psiElement, + final PsiElement psiElement1 + ) throws IncorrectOperationException { xmlTag.deleteChildRange(psiElement, psiElement1); } @Override - public PsiElement replace(@NotNull PsiElement psiElement) throws IncorrectOperationException { + public PsiElement replace( + final @NotNull PsiElement psiElement + ) throws IncorrectOperationException { return xmlTag.replace(psiElement); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public boolean isValid() { return xmlTag.isValid(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public boolean isWritable() { return xmlTag.isWritable(); } @Override - @Nullable - @Contract( - pure = true - ) - public PsiReference getReference() { + @Contract(pure = true) + public @Nullable PsiReference getReference() { return xmlTag.getReference(); } @Override - @NotNull - @Contract( - pure = true - ) - public PsiReference[] getReferences() { + @Contract(pure = true) + public @NotNull PsiReference[] getReferences() { return xmlTag.getReferences(); } @Override - @Nullable - @Contract( - pure = true - ) - public T getCopyableUserData(Key key) { + @Contract(pure = true) + public @Nullable T getCopyableUserData(final Key key) { return xmlTag.getCopyableUserData(key); } @Override - public void putCopyableUserData(Key key, @Nullable T t) { - xmlTag.putCopyableUserData(key, t); + public void putCopyableUserData(final Key key, final @Nullable T value) { + xmlTag.putCopyableUserData(key, value); } @Override - public boolean processDeclarations(@NotNull PsiScopeProcessor psiScopeProcessor, @NotNull ResolveState resolveState, @Nullable PsiElement psiElement, @NotNull PsiElement psiElement1) { + public boolean processDeclarations( + final @NotNull PsiScopeProcessor psiScopeProcessor, + final @NotNull ResolveState resolveState, + final @Nullable PsiElement psiElement, + final @NotNull PsiElement psiElement1 + ) { return xmlTag.processDeclarations(psiScopeProcessor, resolveState, psiElement, psiElement1); } @Override - @Nullable - @Contract( - pure = true - ) - public PsiElement getContext() { + @Contract(pure = true) + public @Nullable PsiElement getContext() { return xmlTag.getContext(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public boolean isPhysical() { return xmlTag.isPhysical(); } @Override - @NotNull - @Contract( - pure = true - ) - public GlobalSearchScope getResolveScope() { + @Contract(pure = true) + public @NotNull GlobalSearchScope getResolveScope() { return xmlTag.getResolveScope(); } @Override - @NotNull - @Contract( - pure = true - ) - public SearchScope getUseScope() { + @Contract(pure = true) + public @NotNull SearchScope getUseScope() { return xmlTag.getUseScope(); } @Override - @Contract( - pure = true - ) + @Contract(pure = true) public ASTNode getNode() { return xmlTag.getNode(); } @Override - @NonNls - @Contract( - pure = true - ) - public String toString() { + @Contract(pure = true) + public @NonNls String toString() { return xmlTag.toString(); } @Override - @Contract( - pure = true - ) - public boolean isEquivalentTo(PsiElement psiElement) { + @Contract(pure = true) + public boolean isEquivalentTo(final PsiElement psiElement) { return xmlTag.isEquivalentTo(psiElement); } @Override - @Nullable - public T getUserData(@NotNull Key key) { + public @Nullable T getUserData(final @NotNull Key key) { return xmlTag.getUserData(key); } @Override - public void putUserData(@NotNull Key key, @Nullable T t) { - xmlTag.putUserData(key, t); + public void putUserData(final @NotNull Key key, final @Nullable T value) { + xmlTag.putUserData(key, value); } @Override - public Icon getIcon(@IconFlags int i) { - return xmlTag.getIcon(i); + public Icon getIcon(final @IconFlags int flags) { + return xmlTag.getIcon(flags); } @Override - public PsiElement setName(@NonNls @NotNull String s) throws IncorrectOperationException { - return xmlTag.setName(s); + public PsiElement setName( + final @NonNls @NotNull String name + ) throws IncorrectOperationException { + return xmlTag.setName(name); } @Override - @Nullable - public PsiMetaData getMetaData() { + public @Nullable PsiMetaData getMetaData() { return xmlTag.getMetaData(); } @Override - @Nullable - public XmlTag getParentTag() { + public @Nullable XmlTag getParentTag() { return xmlTag.getParentTag(); } @Override - @Nullable - public XmlTagChild getNextSiblingInTag() { + public @Nullable XmlTagChild getNextSiblingInTag() { return xmlTag.getNextSiblingInTag(); } @Override - @Nullable - public XmlTagChild getPrevSiblingInTag() { + public @Nullable XmlTagChild getPrevSiblingInTag() { return xmlTag.getPrevSiblingInTag(); } } diff --git a/src/com/magento/idea/magento2plugin/magento/files/Observer.java b/src/com/magento/idea/magento2plugin/magento/files/Observer.java index 22f6dd827..074582d8a 100644 --- a/src/com/magento/idea/magento2plugin/magento/files/Observer.java +++ b/src/com/magento/idea/magento2plugin/magento/files/Observer.java @@ -12,6 +12,9 @@ public class Observer implements ModuleFileInterface { private final String fileName; public static final String INTERFACE = "Magento\\Framework\\Event\\ManagerInterface"; + public static final String IMPLEMENTATION = "Magento\\Framework\\Event\\Manager"; + public static final String ENTITY_IMPL = "Magento\\Framework\\EntityManager\\EventManager"; + public static final String STAGING_IMPL = "Magento\\Staging\\Model\\Event\\Manager"; public static final String DISPATCH_METHOD = "dispatch"; public static final String NAME_ATTRIBUTE = "name"; public static final String OBSERVER_EXECUTE_TEMPLATE_NAME = "Magento Observer Execute Method"; diff --git a/src/com/magento/idea/magento2plugin/magento/packages/MessageQueueConnections.java b/src/com/magento/idea/magento2plugin/magento/packages/MessageQueueConnections.java index e3683914b..a16947659 100644 --- a/src/com/magento/idea/magento2plugin/magento/packages/MessageQueueConnections.java +++ b/src/com/magento/idea/magento2plugin/magento/packages/MessageQueueConnections.java @@ -9,8 +9,9 @@ import java.util.List; public enum MessageQueueConnections { + DB("db"), - AMPQ("ampq"); + AMPQ("amqp"); private final String type; @@ -32,16 +33,6 @@ public String getType() { return type; } - /** - * Get connection type by name. - * - * @param typeName type name - * @return Request Interface - */ - public static String getConnectionTypeByName(final String typeName) { - return MessageQueueConnections.valueOf(typeName).getType(); - } - /** * Get list of connection types. * @@ -51,7 +42,7 @@ public static List getList() { final List typeList = new ArrayList<>(); for (final MessageQueueConnections type: MessageQueueConnections.values()) { - typeList.add(getConnectionTypeByName(type.name())); + typeList.add(type.getType()); } return typeList; diff --git a/src/com/magento/idea/magento2plugin/magento/packages/code/FrameworkLibraryType.java b/src/com/magento/idea/magento2plugin/magento/packages/code/FrameworkLibraryType.java index 8387ba57f..5f60d6ef1 100644 --- a/src/com/magento/idea/magento2plugin/magento/packages/code/FrameworkLibraryType.java +++ b/src/com/magento/idea/magento2plugin/magento/packages/code/FrameworkLibraryType.java @@ -13,6 +13,7 @@ public enum FrameworkLibraryType { ABSTRACT_COLLECTION( "Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection" ), + COMPONENT_REGISTRAR("Magento\\Framework\\Component\\ComponentRegistrar"), COLLECTION_PROCESSOR("Magento\\Framework\\Api\\SearchCriteria\\CollectionProcessorInterface"), DATA_PERSISTOR("Magento\\Framework\\App\\Request\\DataPersistorInterface"), DATA_OBJECT("Magento\\Framework\\DataObject"), diff --git a/src/com/magento/idea/magento2plugin/project/diagnostic/github/GitHubNewIssueBodyBuilderUtil.java b/src/com/magento/idea/magento2plugin/project/diagnostic/github/GitHubNewIssueBodyBuilderUtil.java index 1587edd45..21e06cdcc 100644 --- a/src/com/magento/idea/magento2plugin/project/diagnostic/github/GitHubNewIssueBodyBuilderUtil.java +++ b/src/com/magento/idea/magento2plugin/project/diagnostic/github/GitHubNewIssueBodyBuilderUtil.java @@ -51,13 +51,22 @@ public static String buildNewBugReportBody( if (encode(stackTrace).length() <= maxAllowedStackTraceLength) { return buildTemplate(project, bugDescription, stackTrace); } + boolean isFound = false; + int step = 1; + String encodedCutStackTrace = ""; + + while (!isFound) { + final String cutStackTrace = stackTrace.substring(0, maxAllowedStackTraceLength - step); + encodedCutStackTrace = encode(cutStackTrace); + + if (encodedCutStackTrace.length() <= maxAllowedStackTraceLength) { + isFound = true; + } else { + step += 10; + } + } - final String cutStackTrace = encode(stackTrace).substring( - 0, - maxAllowedStackTraceLength - 1 - ); - - return buildTemplate(project, bugDescription, decode(cutStackTrace)); + return buildTemplate(project, bugDescription, decode(encodedCutStackTrace)); } /** diff --git a/src/com/magento/idea/magento2plugin/reference/provider/PhpClassReferenceProvider.java b/src/com/magento/idea/magento2plugin/reference/provider/PhpClassReferenceProvider.java index 39618e545..58a60a406 100644 --- a/src/com/magento/idea/magento2plugin/reference/provider/PhpClassReferenceProvider.java +++ b/src/com/magento/idea/magento2plugin/reference/provider/PhpClassReferenceProvider.java @@ -5,14 +5,17 @@ package com.magento.idea.magento2plugin.reference.provider; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.PsiReferenceProvider; +import com.intellij.psi.stubs.StubIndex; import com.intellij.util.ProcessingContext; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpNamespace; +import com.jetbrains.php.lang.psi.stubs.indexes.PhpNamespaceIndex; import com.magento.idea.magento2plugin.reference.xml.PolyVariantReferenceBase; import com.magento.idea.magento2plugin.util.RegExUtil; import java.util.ArrayList; @@ -26,13 +29,11 @@ @SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops"}) public class PhpClassReferenceProvider extends PsiReferenceProvider { - @NotNull @Override - public PsiReference[] getReferencesByElement( + public @NotNull PsiReference[] getReferencesByElement( final @NotNull PsiElement element, final @NotNull ProcessingContext context ) { - final String origValue = element.getText(); final Pattern pattern = Pattern.compile(RegExUtil.PhpRegex.FQN); @@ -49,15 +50,21 @@ public PsiReference[] getReferencesByElement( final StringBuilder namespace = new StringBuilder(); String namespacePart; final List psiReferences = new ArrayList<>(); + for (int i = 0; i < fqnParts.length - 1; i++) { namespacePart = fqnParts[i]; + namespace.append('\\'); + namespace.append(namespacePart); + + final String namespaceId = namespace + .toString() + .toLowerCase(new Locale("en","EN")); + + final Collection references = hasNamespaceInIndex( + namespaceId, + element.getProject() + ) ? phpIndex.getNamespacesByName(namespaceId) : new ArrayList<>(); - namespace.append("\\");//NOPMD - namespace.append(namespacePart);//NOPMD - final Collection references = - phpIndex.getNamespacesByName(namespace.toString().toLowerCase( - new Locale("en","EN")) - ); if (!references.isEmpty()) { final TextRange range = new TextRange( origValue.indexOf(classFQN) + namespace.toString().lastIndexOf(92), @@ -67,17 +74,42 @@ public PsiReference[] getReferencesByElement( psiReferences.add(new PolyVariantReferenceBase(element, range, references)); } } - final String className = classFQN.substring(classFQN.lastIndexOf(92) + 1); - final Collection classes = phpIndex.getAnyByFQN(classFQN); - if (!classes.isEmpty()) { - final TextRange range = new TextRange( - origValue.lastIndexOf(92) + 1, - origValue.lastIndexOf(92) + 1 + className.length() - ); - psiReferences.add(new PolyVariantReferenceBase(element, range, classes)); + + try { + final Collection classes = phpIndex.getAnyByFQN(classFQN); + + if (!classes.isEmpty()) { + final TextRange range = new TextRange( + origValue.lastIndexOf(92) + 1, + origValue.lastIndexOf(92) + 1 + className.length() + ); + psiReferences.add(new PolyVariantReferenceBase(element, range, classes)); + } + } catch (Exception exception) { //NOPMD + return psiReferences.toArray(new PsiReference[0]); } return psiReferences.toArray(new PsiReference[0]); } + + /** + * Check if php namespace index has specified identifier. + * + * @param namespaceIdentifier String + * @param project Project + * + * @return boolean + */ + private boolean hasNamespaceInIndex( + final @NotNull String namespaceIdentifier, + final @NotNull Project project + ) { + final Collection keys = StubIndex.getInstance().getAllKeys( + PhpNamespaceIndex.KEY, + project + ); + + return keys.contains(namespaceIdentifier); + } } diff --git a/src/com/magento/idea/magento2plugin/stubs/indexes/WebApiTypeIndex.java b/src/com/magento/idea/magento2plugin/stubs/indexes/WebApiTypeIndex.java index cc2bd34a2..f792e6c30 100644 --- a/src/com/magento/idea/magento2plugin/stubs/indexes/WebApiTypeIndex.java +++ b/src/com/magento/idea/magento2plugin/stubs/indexes/WebApiTypeIndex.java @@ -1,7 +1,8 @@ -/** +/* * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.stubs.indexes; import com.intellij.ide.highlighter.XmlFileType; @@ -13,41 +14,48 @@ import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; -import com.intellij.util.indexing.*; +import com.intellij.util.indexing.DataIndexer; +import com.intellij.util.indexing.FileBasedIndex; +import com.intellij.util.indexing.FileContent; +import com.intellij.util.indexing.ID; +import com.intellij.util.indexing.ScalarIndexExtension; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.jetbrains.php.lang.PhpLangUtil; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; -import com.magento.idea.magento2plugin.project.Settings; import com.magento.idea.magento2plugin.linemarker.xml.LineMarkerXmlTagDecorator; +import com.magento.idea.magento2plugin.project.Settings; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import java.util.*; - /** * Indexer for classes/interfaces which have methods exposed via Web API. */ public class WebApiTypeIndex extends ScalarIndexExtension { - public static final ID KEY = ID.create("com.magento.idea.magento2plugin.stubs.indexes.webapi_type"); - + public static final ID KEY = ID.create( + "com.magento.idea.magento2plugin.stubs.indexes.webapi_type" + ); private final KeyDescriptor keyDescriptor = new EnumeratorStringDescriptor(); - @NotNull @Override - public ID getName() { + public @NotNull ID getName() { return KEY; } - @NotNull + @SuppressWarnings("PMD.CognitiveComplexity") @Override - public DataIndexer getIndexer() { + public @NotNull DataIndexer getIndexer() { return inputData -> { - Map map = new HashMap<>(); + final Map map = new HashMap<>(); + final PsiFile psiFile = inputData.getPsiFile(); - PsiFile psiFile = inputData.getPsiFile(); if (!Settings.isEnabled(psiFile.getProject())) { return map; } @@ -55,22 +63,26 @@ public DataIndexer getIndexer() { if (!(psiFile instanceof XmlFile)) { return map; } + final XmlDocument document = ((XmlFile) psiFile).getDocument(); - XmlDocument document = ((XmlFile) psiFile).getDocument(); if (document == null) { return map; } + final XmlTag[] xmlTags = PsiTreeUtil.getChildrenOfType( + psiFile.getFirstChild(), + XmlTag.class + ); - XmlTag xmlTags[] = PsiTreeUtil.getChildrenOfType(psiFile.getFirstChild(), XmlTag.class); if (xmlTags == null) { return map; } - for (XmlTag xmlTag : xmlTags) { - if (xmlTag.getName().equals("routes")) { - for (XmlTag routeNode : xmlTag.findSubTags("route")) { - for (XmlTag serviceNode : routeNode.findSubTags("service")) { - String typeName = serviceNode.getAttributeValue("class"); + for (final XmlTag xmlTag : xmlTags) { + if ("routes".equals(xmlTag.getName())) { + for (final XmlTag routeNode : xmlTag.findSubTags("route")) { + for (final XmlTag serviceNode : routeNode.findSubTags("service")) { + final String typeName = serviceNode.getAttributeValue("class"); + if (typeName != null) { map.put(PhpLangUtil.toPresentableFQN(typeName), null); } @@ -78,23 +90,21 @@ public DataIndexer getIndexer() { } } } + return map; }; } - @NotNull @Override - public KeyDescriptor getKeyDescriptor() { + public @NotNull KeyDescriptor getKeyDescriptor() { return keyDescriptor; } - @NotNull @Override - public FileBasedIndex.InputFilter getInputFilter() { - return file -> ( - file.getFileType() == XmlFileType.INSTANCE && file.getNameWithoutExtension().equals("webapi") - && !file.getPath().contains("testsuite") && !file.getPath().contains("_files") - ); + public @NotNull FileBasedIndex.InputFilter getInputFilter() { + return file -> file.getFileType() == XmlFileType.INSTANCE + && "webapi".equals(file.getNameWithoutExtension()) + && !file.getPath().contains("testsuite") && !file.getPath().contains("_files"); } @Override @@ -109,45 +119,77 @@ public int getVersion() { /** * Get list of Web API routes associated with the provided method. - * * Parent classes are not taken into account. + * + * @param method Method + * + * @return List[XmlTag] */ - public static List getWebApiRoutes(Method method) { - List tags = new ArrayList<>(); + public static List getWebApiRoutes(final Method method) { + final List tags = new ArrayList<>(); + if (!method.getAccess().isPublic()) { return tags; } - PhpClass phpClass = method.getContainingClass(); - String methodFqn = method.getName(); + final PhpClass phpClass = method.getContainingClass(); + if (phpClass == null) { return tags; } - String classFqn = phpClass.getPresentableFQN(); - Collection containingFiles = FileBasedIndex - .getInstance().getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject())); + final String classFqn = phpClass.getPresentableFQN(); + final Collection containingFiles = FileBasedIndex + .getInstance() + .getContainingFiles( + KEY, + classFqn, + GlobalSearchScope.allScope(phpClass.getProject()) + ); + + final PsiManager psiManager = PsiManager.getInstance(phpClass.getProject()); + final String methodFqn = method.getName(); + + for (final VirtualFile virtualFile : containingFiles) { + if (virtualFile.getFileType() != XmlFileType.INSTANCE) { + continue; + } + final XmlFile file = (XmlFile) psiManager.findFile(virtualFile); - PsiManager psiManager = PsiManager.getInstance(phpClass.getProject()); - for (VirtualFile virtualFile : containingFiles) { - XmlFile file = (XmlFile) psiManager.findFile(virtualFile); if (file == null) { continue; } - XmlTag rootTag = file.getRootTag(); + final XmlTag rootTag = file.getRootTag(); + + if (rootTag == null) { + continue; + } fillRelatedTags(classFqn, methodFqn, rootTag, tags); } + return tags; } /** - * Find routes related to the specified method within single webapi.xml + * Find routes related to the specified method within single webapi.xml. + * + * @param classFqn String + * @param methodFqn String + * @param parentTag XmlTag + * @param tagsReferences List[XmlTag] */ - private static void fillRelatedTags(String classFqn, String methodFqn, XmlTag parentTag, List tagsReferences) { - for (XmlTag routeNode : parentTag.findSubTags("route")) { - for (XmlTag serviceNode : routeNode.findSubTags("service")) { - String typeName = serviceNode.getAttributeValue("class"); - String methodName = serviceNode.getAttributeValue("method"); + @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") + private static void fillRelatedTags( + final String classFqn, + final String methodFqn, + final XmlTag parentTag, + final List tagsReferences + ) { + for (final XmlTag routeNode : parentTag.findSubTags("route")) { + for (final XmlTag serviceNode : routeNode.findSubTags("service")) { + final String typeName = serviceNode.getAttributeValue("class"); + final String methodName = serviceNode.getAttributeValue("method"); + if (typeName != null && typeName.equals(classFqn) - && methodName != null && methodName.equals(methodFqn) + && methodName != null && methodName.equals(methodFqn) ) { tagsReferences.add(new WebApiLineMarkerXmlTagDecorator(routeNode)); } @@ -160,25 +202,24 @@ private static void fillRelatedTags(String classFqn, String methodFqn, XmlTag pa */ private static class WebApiLineMarkerXmlTagDecorator extends LineMarkerXmlTagDecorator { - WebApiLineMarkerXmlTagDecorator(XmlTag xmlTag) { + public WebApiLineMarkerXmlTagDecorator(final XmlTag xmlTag) { super(xmlTag); } - @NotNull @Override - public String getDescription() { + public @NotNull String getDescription() { return ""; } @Override - @NotNull - @NonNls - public String getName() { - String httpMethod = this.xmlTag.getAttributeValue("method"); - String route = this.xmlTag.getAttributeValue("url"); + public @NonNls @NotNull String getName() { + final String httpMethod = this.xmlTag.getAttributeValue("method"); + final String route = this.xmlTag.getAttributeValue("url"); + if (httpMethod != null && route != null) { return String.format(" %-7s %s", httpMethod, route); } + return xmlTag.getName(); } } diff --git a/src/com/magento/idea/magento2plugin/stubs/indexes/graphql/GraphQlResolverIndex.java b/src/com/magento/idea/magento2plugin/stubs/indexes/graphql/GraphQlResolverIndex.java index e3dd7ffb2..35f80af4f 100644 --- a/src/com/magento/idea/magento2plugin/stubs/indexes/graphql/GraphQlResolverIndex.java +++ b/src/com/magento/idea/magento2plugin/stubs/indexes/graphql/GraphQlResolverIndex.java @@ -2,22 +2,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.stubs.indexes.graphql; import com.intellij.lang.jsgraphql.GraphQLFileType; -import com.intellij.lang.jsgraphql.psi.*; +import com.intellij.lang.jsgraphql.psi.GraphQLArgument; +import com.intellij.lang.jsgraphql.psi.GraphQLArguments; +import com.intellij.lang.jsgraphql.psi.GraphQLDirective; +import com.intellij.lang.jsgraphql.psi.GraphQLFieldDefinition; +import com.intellij.lang.jsgraphql.psi.GraphQLFieldsDefinition; +import com.intellij.lang.jsgraphql.psi.GraphQLFile; +import com.intellij.lang.jsgraphql.psi.GraphQLInterfaceTypeDefinition; +import com.intellij.lang.jsgraphql.psi.GraphQLObjectTypeDefinition; +import com.intellij.lang.jsgraphql.psi.GraphQLQuotedString; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.indexing.*; +import com.intellij.util.indexing.DataIndexer; +import com.intellij.util.indexing.FileBasedIndex; +import com.intellij.util.indexing.FileContent; +import com.intellij.util.indexing.ID; +import com.intellij.util.indexing.ScalarIndexExtension; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.magento.idea.magento2plugin.util.magento.graphql.GraphQlUtil; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jetbrains.annotations.NotNull; -import java.util.*; +@SuppressWarnings({"PMD.ExcessiveImports"}) public class GraphQlResolverIndex extends ScalarIndexExtension { public static final ID KEY = ID.create("com.magento.idea.magento2plugin.stubs.indexes.resolver_usages"); @@ -30,28 +49,30 @@ public ID getName() { @NotNull @Override + @SuppressWarnings({"PMD.CognitiveComplexity", "PMD.NPathComplexity"}) public DataIndexer getIndexer() { return inputData -> { - Map map = new HashMap<>(); + final Map map = new HashMap<>(); - GraphQLFile graphQLFile = (GraphQLFile) inputData.getPsiFile(); - PsiElement[] children = graphQLFile.getChildren(); - for (PsiElement child : children) { - if (!(child instanceof GraphQLObjectTypeDefinition) && !(child instanceof GraphQLInterfaceTypeDefinition)) { + final GraphQLFile graphQLFile = (GraphQLFile) inputData.getPsiFile(); + final PsiElement[] children = graphQLFile.getChildren(); + for (final PsiElement child : children) { + if (!(child instanceof GraphQLObjectTypeDefinition) + && !(child instanceof GraphQLInterfaceTypeDefinition)) { continue; } - PsiElement[] objectChildren = child.getChildren(); - for (PsiElement objectChild : objectChildren) { + final PsiElement[] objectChildren = child.getChildren(); + for (final PsiElement objectChild : objectChildren) { if (!(objectChild instanceof GraphQLFieldsDefinition)) { continue; } - PsiElement[] fieldsChildren = objectChild.getChildren(); - for (PsiElement fieldsChild : fieldsChildren) { + final PsiElement[] fieldsChildren = objectChild.getChildren(); + for (final PsiElement fieldsChild : fieldsChildren) { if (!(fieldsChild instanceof GraphQLFieldDefinition)) { continue; } - PsiElement[] fieldChildren = fieldsChild.getChildren(); - for (PsiElement fieldChild : fieldChildren) { + final PsiElement[] fieldChildren = fieldsChild.getChildren(); + for (final PsiElement fieldChild : fieldChildren) { if (!(fieldChild instanceof GraphQLDirective)) { continue; } @@ -59,21 +80,26 @@ public DataIndexer getIndexer() { continue; } - PsiElement[] directiveChildren = fieldChild.getChildren(); + final PsiElement[] directiveChildren = fieldChild.getChildren(); - for (PsiElement directiveChild : directiveChildren) { + for (final PsiElement directiveChild : directiveChildren) { if (!(directiveChild instanceof GraphQLArguments)) { continue; } - PsiElement[] argumentsChildren = directiveChild.getChildren(); - for (PsiElement argumentsChild : argumentsChildren) { + final PsiElement[] argumentsChildren = directiveChild.getChildren(); + for (final PsiElement argumentsChild : argumentsChildren) { if (!(argumentsChild instanceof GraphQLArgument)) { continue; } - PsiElement argumentStringValue = GraphQlUtil.fetchResolverQuotedStringFromArgument(argumentsChild); - if (argumentStringValue == null) continue; + final PsiElement argumentStringValue = + GraphQlUtil.fetchResolverQuotedStringFromArgument( + argumentsChild + ); + if (argumentStringValue == null) { + continue; + } String resolverFQN = argumentStringValue.getText(); if (resolverFQN == null) { @@ -103,8 +129,8 @@ public KeyDescriptor getKeyDescriptor() { @NotNull @Override public FileBasedIndex.InputFilter getInputFilter() { - return virtualFile -> (virtualFile.getFileType() == GraphQLFileType.INSTANCE - && virtualFile.getName().equals("schema.graphqls")); + return virtualFile -> virtualFile.getFileType() == GraphQLFileType.INSTANCE + && "schema.graphqls".equals(virtualFile.getName()); } @Override @@ -117,28 +143,44 @@ public int getVersion() { return 1; } - - public static List getGraphQLUsages(@NotNull PhpClass phpClass) { - List quotedStrings = new ArrayList<>(); - - String classFqn = phpClass.getFQN(); - Collection containingFiles = FileBasedIndex - .getInstance().getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject())); - - PsiManager psiManager = PsiManager.getInstance(phpClass.getProject()); - for (VirtualFile virtualFile : containingFiles) { - GraphQLFile file = (GraphQLFile) psiManager.findFile(virtualFile); - if (file == null) { + /** + * Get GraphQL Usages. + * + * @param phpClass PhpClass + * + * @return List[GraphQLQuotedString] + */ + public static List getGraphQLUsages(final @NotNull PhpClass phpClass) { + final List quotedStrings = new ArrayList<>(); + + final String classFqn = phpClass.getFQN(); + final Collection containingFiles = FileBasedIndex + .getInstance().getContainingFiles( + KEY, + classFqn, + GlobalSearchScope.allScope(phpClass.getProject()) + ); + + final PsiManager psiManager = PsiManager.getInstance(phpClass.getProject()); + for (final VirtualFile virtualFile : containingFiles) { + final PsiFile fileCandidate = psiManager.findFile(virtualFile); + + if (!(fileCandidate instanceof GraphQLFile)) { continue; } - PsiElement[] children = file.getChildren(); + final GraphQLFile file = (GraphQLFile) fileCandidate; + final PsiElement[] children = file.getChildren(); findMatchingQuotedString(children, classFqn, quotedStrings); } return quotedStrings; } - private static PsiElement findMatchingQuotedString(PsiElement[] psiElements, String classFqn, List quotedStrings) { - for (PsiElement element: psiElements) { + private static PsiElement findMatchingQuotedString( + final PsiElement[] psiElements, + final String classFqn, + final List quotedStrings + ) { + for (final PsiElement element: psiElements) { if (!(element instanceof GraphQLArgument) && element.getChildren().length == 0) { continue; } @@ -147,16 +189,19 @@ private static PsiElement findMatchingQuotedString(PsiElement[] psiElements, Str continue; } - PsiElement argumentStringValue = GraphQlUtil.fetchResolverQuotedStringFromArgument(element); - if (argumentStringValue == null) continue; + final PsiElement argumentStringValue = + GraphQlUtil.fetchResolverQuotedStringFromArgument(element); + if (argumentStringValue == null) { + continue; + } String resolverFQN = argumentStringValue.getText(); if (resolverFQN == null) { return null; } - + resolverFQN = GraphQlUtil.resolverStringToPhpFQN(resolverFQN); - + if (!resolverFQN.equals(classFqn)) { continue; } diff --git a/src/com/magento/idea/magento2plugin/stubs/indexes/js/RequireJsIndex.java b/src/com/magento/idea/magento2plugin/stubs/indexes/js/RequireJsIndex.java index 4fd74fc9f..065e68709 100644 --- a/src/com/magento/idea/magento2plugin/stubs/indexes/js/RequireJsIndex.java +++ b/src/com/magento/idea/magento2plugin/stubs/indexes/js/RequireJsIndex.java @@ -2,68 +2,71 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + package com.magento.idea.magento2plugin.stubs.indexes.js; import com.intellij.lang.javascript.JavaScriptFileType; -import com.intellij.lang.javascript.psi.*; +import com.intellij.lang.javascript.psi.JSExpression; +import com.intellij.lang.javascript.psi.JSFile; +import com.intellij.lang.javascript.psi.JSObjectLiteralExpression; +import com.intellij.lang.javascript.psi.JSProperty; +import com.intellij.lang.javascript.psi.JSVarStatement; +import com.intellij.lang.javascript.psi.JSVariable; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.indexing.*; +import com.intellij.util.indexing.DataIndexer; +import com.intellij.util.indexing.FileBasedIndex; +import com.intellij.util.indexing.FileBasedIndexExtension; +import com.intellij.util.indexing.FileContent; +import com.intellij.util.indexing.ID; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; -import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; +import org.jetbrains.annotations.NotNull; public class RequireJsIndex extends FileBasedIndexExtension { - public static final ID KEY = - ID.create("com.magento.idea.magento2plugin.stubs.indexes.require_js"); - @NotNull + public static final ID KEY = ID.create( + "com.magento.idea.magento2plugin.stubs.indexes.require_js" + ); + @Override - public ID getName() { + public @NotNull ID getName() { return KEY; } - @NotNull @Override - public DataIndexer getIndexer() { + public @NotNull DataIndexer getIndexer() { return inputData -> { - Map map = new HashMap<>(); - JSFile jsFile = (JSFile)inputData.getPsiFile(); + final Map map = new HashMap<>(); + final JSFile jsFile = (JSFile) inputData.getPsiFile(); + + final JSVarStatement jsVarStatement = PsiTreeUtil.getChildOfType( + jsFile, + JSVarStatement.class + ); - JSVarStatement jsVarStatement = PsiTreeUtil.getChildOfType(jsFile, JSVarStatement.class); if (jsVarStatement == null) { return map; } - JSVariable[] jsVariableList = jsVarStatement.getVariables(); - for (JSVariable jsVariable : jsVariableList) { - String name = jsVariable.getName(); - if (name.equals("config")) { - JSObjectLiteralExpression config = PsiTreeUtil.getChildOfType(jsVariable, JSObjectLiteralExpression.class); + final JSVariable[] jsVariableList = jsVarStatement.getVariables(); + + for (final JSVariable jsVariable : jsVariableList) { + final String name = jsVariable.getName(); + + if ("config".equals(name)) { + final JSObjectLiteralExpression config = PsiTreeUtil.getChildOfType( + jsVariable, + JSObjectLiteralExpression.class + ); + if (config == null) { return map; } parseConfigMap(map, config); - - JSProperty pathsMap = config.findProperty("paths"); - if (pathsMap == null) { - return map; - } - JSObjectLiteralExpression[] pathGroupsWrappers = PsiTreeUtil.getChildrenOfType(pathsMap, JSObjectLiteralExpression.class); - for (JSObjectLiteralExpression pathGroupsWrapper : pathGroupsWrappers) { - JSProperty[] allConfigs = pathGroupsWrapper.getProperties(); - for (JSProperty mapping : allConfigs) { - String nameConfig = mapping.getName(); - JSExpression value = mapping.getValue(); - if (value == null) { - continue; - } - String valueConfig = value.getText(); - map.put(nameConfig, valueConfig); - } - } + parseConfigPaths(map, config); } } @@ -71,45 +74,87 @@ public DataIndexer getIndexer() { }; } - private void parseConfigMap(Map map, JSObjectLiteralExpression config) { - JSProperty configMap = config.findProperty("map"); + private void parseConfigMap( + final Map map, + final JSObjectLiteralExpression config + ) { + final JSProperty configMap = config.findProperty("map"); + if (configMap == null) { return; } + final JSObjectLiteralExpression[] configGroupsWrappers = PsiTreeUtil.getChildrenOfType( + configMap, + JSObjectLiteralExpression.class + ); + if (configGroupsWrappers == null) { + return; + } - JSObjectLiteralExpression[] configGroupsWrappers = PsiTreeUtil.getChildrenOfType(configMap, JSObjectLiteralExpression.class); - for (JSObjectLiteralExpression configGroupsWrapper : configGroupsWrappers) { - PsiElement[] configGroups = configGroupsWrapper.getChildren(); + for (final JSObjectLiteralExpression configGroupsWrapper : configGroupsWrappers) { + final PsiElement[] configGroups = configGroupsWrapper.getChildren(); - for (PsiElement configGroup : configGroups) { - JSObjectLiteralExpression mappingWrapper = PsiTreeUtil.getChildOfType(configGroup, JSObjectLiteralExpression.class); - JSProperty[] allConfigs = mappingWrapper.getProperties(); + for (final PsiElement configGroup : configGroups) { + final JSObjectLiteralExpression mappingWrapper = PsiTreeUtil.getChildOfType( + configGroup, + JSObjectLiteralExpression.class + ); - for (JSProperty mapping : allConfigs) { - String nameConfig = mapping.getName(); - JSExpression value = mapping.getValue(); - if (value == null) { - continue; - } - String valueConfig = value.getText(); - map.put(nameConfig, valueConfig); + if (mappingWrapper == null) { + continue; } + processObjectProperties(map, mappingWrapper.getProperties()); } } } - @NotNull + private void parseConfigPaths( + final Map map, + final JSObjectLiteralExpression config + ) { + final JSProperty pathsMap = config.findProperty("paths"); + + if (pathsMap == null) { + return; + } + final JSObjectLiteralExpression[] pathGroupsWrappers = PsiTreeUtil + .getChildrenOfType(pathsMap, JSObjectLiteralExpression.class); + + if (pathGroupsWrappers == null) { + return; + } + + for (final JSObjectLiteralExpression pathGroupsWrapper : pathGroupsWrappers) { + processObjectProperties(map, pathGroupsWrapper.getProperties()); + } + } + + private void processObjectProperties( + final Map map, + final JSProperty... allConfigs + ) { + for (final JSProperty mapping : allConfigs) { + final String nameConfig = mapping.getName(); + final JSExpression value = mapping.getValue(); + + if (value == null) { + continue; + } + final String valueConfig = value.getText(); + map.put(nameConfig, valueConfig); + } + } + @Override - public KeyDescriptor getKeyDescriptor() { + public @NotNull KeyDescriptor getKeyDescriptor() { return new EnumeratorStringDescriptor(); } - @NotNull @Override - public FileBasedIndex.InputFilter getInputFilter() { - return virtualFile -> ( - virtualFile.getFileType().equals(JavaScriptFileType.INSTANCE) && virtualFile.getName().equals("requirejs-config.js") - ); + public @NotNull FileBasedIndex.InputFilter getInputFilter() { + return virtualFile -> + virtualFile.getFileType().equals(JavaScriptFileType.INSTANCE) + && "requirejs-config.js".equals(virtualFile.getName()); } @Override @@ -122,8 +167,8 @@ public int getVersion() { return 1; } - @NotNull - public DataExternalizer getValueExternalizer() { + @Override + public @NotNull DataExternalizer getValueExternalizer() { return EnumeratorStringDescriptor.INSTANCE; } } diff --git a/src/com/magento/idea/magento2plugin/util/magento/GetModuleNameByDirectoryUtil.java b/src/com/magento/idea/magento2plugin/util/magento/GetModuleNameByDirectoryUtil.java index 84b9c1ec3..a7e882ba5 100644 --- a/src/com/magento/idea/magento2plugin/util/magento/GetModuleNameByDirectoryUtil.java +++ b/src/com/magento/idea/magento2plugin/util/magento/GetModuleNameByDirectoryUtil.java @@ -16,6 +16,7 @@ import com.magento.idea.magento2plugin.util.RegExUtil; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class GetModuleNameByDirectoryUtil { @@ -27,18 +28,21 @@ private GetModuleNameByDirectoryUtil() {} * * @param psiDirectory PsiDirectory * @param project Project + * * @return String */ - public static String execute( - final PsiDirectory psiDirectory, - final Project project + public static @Nullable String execute( + final @NotNull PsiDirectory psiDirectory, + final @NotNull Project project ) { // Check if directory is theme directory and return module name from directory path if yes final String path = psiDirectory.getVirtualFile().getPath(); final Pattern pattern = Pattern.compile(RegExUtil.CustomTheme.MODULE_NAME); final Matcher matcher = pattern.matcher(path); + while (matcher.find()) { final String moduleNamePath = matcher.group(0); + if (!moduleNamePath.isEmpty()) { return moduleNamePath.split("/")[5]; } @@ -48,33 +52,39 @@ public static String execute( psiDirectory, project ); + if (registrationPhp == null) { return null; } final PsiElement[] childElements = registrationPhp.getChildren(); + if (childElements.length == 0) { return null; } + return getModuleName(childElements); } - private static MethodReference[] parseRegistrationPhpElements(//NOPMD + private static MethodReference[] parseRegistrationPhpElements( final PsiElement... elements ) { - for (final PsiElement element: elements) { + for (final PsiElement element : elements) { MethodReference[] methods = PsiTreeUtil.getChildrenOfType( element, MethodReference.class ); + if (methods == null) { final PsiElement[] children = element.getChildren(); methods = parseRegistrationPhpElements(children); } - if (methods != null) { + + if (methods.length > 0) { return methods; } } - return null; + + return new MethodReference[0]; } private static PhpFile getRegistrationPhpRecursively( @@ -99,25 +109,30 @@ private static PhpFile getRegistrationPhpRecursively( private static String getModuleName(final PsiElement... childElements) { final MethodReference[] methods = parseRegistrationPhpElements(childElements); - if (methods == null) { + + if (methods.length == 0) { return null; } + for (final MethodReference method: methods) { - if (!method.getName().equals(RegistrationPhp.REGISTER_METHOD_NAME)) { + if (!RegistrationPhp.REGISTER_METHOD_NAME.equals(method.getName())) { continue; } final PsiElement[] parameters = method.getParameters(); + for (final PsiElement parameter: parameters) { if (!(parameter instanceof StringLiteralExpression)) { continue; } final String moduleName = ((StringLiteralExpression) parameter) .getContents(); + if (moduleName.matches(RegExUtil.Magento.MODULE_NAME)) { return moduleName; } } } + return null; } @@ -131,11 +146,13 @@ private static PhpFile getModuleRegistrationPhpFile( continue; } final String filename = ((PhpFile) containingFile).getName(); - if (filename.equals(RegistrationPhp.FILE_NAME)) { + + if (RegistrationPhp.FILE_NAME.equals(filename)) { return (PhpFile) containingFile; } } } + return null; } } diff --git a/src/com/magento/idea/magento2uct/packages/SupportedVersion.java b/src/com/magento/idea/magento2uct/packages/SupportedVersion.java index fd1306987..aae7e66c2 100644 --- a/src/com/magento/idea/magento2uct/packages/SupportedVersion.java +++ b/src/com/magento/idea/magento2uct/packages/SupportedVersion.java @@ -38,8 +38,7 @@ public enum SupportedVersion { V2422("2.4.2-p2"), V243("2.4.3"), V2431("2.4.3-p1"), - V2441("2.4.4-beta1"), - V2442("2.4.4-beta2"); + V2444("2.4.4-beta4"); private final String version; diff --git a/src/com/magento/idea/magento2uct/ui/ConfigurationDialog.java b/src/com/magento/idea/magento2uct/ui/ConfigurationDialog.java index d552d6d95..039b430ba 100644 --- a/src/com/magento/idea/magento2uct/ui/ConfigurationDialog.java +++ b/src/com/magento/idea/magento2uct/ui/ConfigurationDialog.java @@ -156,7 +156,7 @@ private void onOK() { ); settingsService.setIgnoreCurrentVersion(ignoreCurrentVersion.isSelected()); - this.setVisible(false); + exit(); } /** diff --git a/src/com/magento/idea/magento2uct/ui/ReindexDialog.java b/src/com/magento/idea/magento2uct/ui/ReindexDialog.java index af1ffb30c..f0f23ab0a 100644 --- a/src/com/magento/idea/magento2uct/ui/ReindexDialog.java +++ b/src/com/magento/idea/magento2uct/ui/ReindexDialog.java @@ -125,7 +125,7 @@ private void onOK() { ); executor.run(); - this.setVisible(false); + exit(); } /** diff --git a/src/com/magento/idea/magento2uct/util/php/MagentoTypeEscapeUtil.java b/src/com/magento/idea/magento2uct/util/php/MagentoTypeEscapeUtil.java index 7f6d37b84..ce910cea9 100644 --- a/src/com/magento/idea/magento2uct/util/php/MagentoTypeEscapeUtil.java +++ b/src/com/magento/idea/magento2uct/util/php/MagentoTypeEscapeUtil.java @@ -32,7 +32,13 @@ private MagentoTypeEscapeUtil() { String result = typeFqn; while (matcher.find()) { - result = result.substring(0, matcher.start(0)) + result.substring(matcher.end(0)); + final int begin = matcher.start(0); + final int end = matcher.end(0); + + if (begin < 0 || begin > end || end > result.length()) { + continue; + } + result = result.substring(0, begin) + result.substring(end); } return typeFqn.equals(result) ? typeFqn : result; diff --git a/src/com/magento/idea/magento2uct/versioning/VersionStateManager.java b/src/com/magento/idea/magento2uct/versioning/VersionStateManager.java index b94dc713e..aa89ea5ca 100644 --- a/src/com/magento/idea/magento2uct/versioning/VersionStateManager.java +++ b/src/com/magento/idea/magento2uct/versioning/VersionStateManager.java @@ -24,8 +24,8 @@ public final class VersionStateManager { private final ExistenceStateIndex existenceStateIndex; private final ApiCoverageStateIndex apiCoverageStateIndex; private final Boolean isSetIgnoreFlag; - private final SupportedVersion currentVersion; - private final SupportedVersion targetVersion; + private SupportedVersion currentVersion; + private SupportedVersion targetVersion; private final List versionsToLoad; /** @@ -48,6 +48,7 @@ public static synchronized VersionStateManager getInstance( )) { instance = new VersionStateManager(project); } + return instance; } @@ -115,6 +116,8 @@ private VersionStateManager(final @NotNull Project project) { currentVersion = settingsService.getCurrentVersionOrDefault(); targetVersion = settingsService.getTargetVersion(); versionsToLoad = new LinkedList<>(); + // Correct settings if stored data isn't valid for current supported versions state. + correctSettings(project); deprecationStateIndex = new DeprecationStateIndex(); compute(deprecationStateIndex); @@ -126,6 +129,35 @@ private VersionStateManager(final @NotNull Project project) { compute(apiCoverageStateIndex); } + /** + * Correct settings if corrupted. + * + * @param project Project + */ + @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") + private synchronized void correctSettings(final @NotNull Project project) { + final UctSettingsService settingsService = UctSettingsService.getInstance(project); + final List allVersions = SupportedVersion.getSupportedVersions(); + + if (currentVersion == null + || SupportedVersion.getVersion(currentVersion.getVersion()) == null) { + final SupportedVersion correctCurrentVersion = SupportedVersion.getVersion( + allVersions.get(0) + ); + settingsService.setCurrentVersion(correctCurrentVersion); + currentVersion = correctCurrentVersion; + } + + if (targetVersion == null + || SupportedVersion.getVersion(targetVersion.getVersion()) == null) { + final SupportedVersion correctTargetVersion = SupportedVersion.getVersion( + allVersions.get(allVersions.size() - 1) + ); + settingsService.setTargetVersion(correctTargetVersion); + targetVersion = correctTargetVersion; + } + } + /** * Check if current instance is valid for settings. * diff --git a/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateFileInRoot/composer.json b/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateFileInRoot/composer.json index fd8914d3b..70fc28282 100644 --- a/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateFileInRoot/composer.json +++ b/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateFileInRoot/composer.json @@ -5,8 +5,8 @@ "type": "magento2-module", "require": { "magento/framework": "*", - "foo/bar": "*", - "magento/backend": "*" + "foo/bar": "1.0.*", + "magento/module-backend": "103.0.*" }, "license": [ "Test License 1", diff --git a/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateModuleFile/composer.json b/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateModuleFile/composer.json index fd8914d3b..70fc28282 100644 --- a/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateModuleFile/composer.json +++ b/testData/actions/generation/generator/ModuleComposerJsonGenerator/generateModuleFile/composer.json @@ -5,8 +5,8 @@ "type": "magento2-module", "require": { "magento/framework": "*", - "foo/bar": "*", - "magento/backend": "*" + "foo/bar": "1.0.*", + "magento/module-backend": "103.0.*" }, "license": [ "Test License 1", diff --git a/testData/project/magento2/vendor/magento/framework/Component/ComponentRegistrar.php b/testData/project/magento2/vendor/magento/framework/Component/ComponentRegistrar.php new file mode 100644 index 000000000..7fea9a4e9 --- /dev/null +++ b/testData/project/magento2/vendor/magento/framework/Component/ComponentRegistrar.php @@ -0,0 +1,87 @@ + [], + self::LIBRARY => [], + self::LANGUAGE => [], + self::THEME => [], + self::SETUP => [] + ]; + + /** + * Sets the location of a component. + * + * @param string $type component type + * @param string $componentName Fully-qualified component name + * @param string $path Absolute file path to the component + * @throws \LogicException + * @return void + */ + public static function register($type, $componentName, $path) + { + self::validateType($type); + if (isset(self::$paths[$type][$componentName])) { + throw new \LogicException( + ucfirst($type) . ' \'' . $componentName . '\' from \'' . $path . '\' ' + . 'has been already defined in \'' . self::$paths[$type][$componentName] . '\'.' + ); + } + self::$paths[$type][$componentName] = str_replace('\\', '/', $path); + } + + /** + * @inheritdoc + */ + public function getPaths($type) + { + self::validateType($type); + return self::$paths[$type]; + } + + /** + * @inheritdoc + */ + public function getPath($type, $componentName) + { + self::validateType($type); + return self::$paths[$type][$componentName] ?? null; + } + + /** + * Checks if type of component is valid + * + * @param string $type + * @return void + * @throws \LogicException + */ + private static function validateType($type) + { + if (!isset(self::$paths[$type])) { + throw new \LogicException('\'' . $type . '\' is not a valid component type'); + } + } +}