diff --git a/build.gradle.kts b/build.gradle.kts index f89e6aa..d3d2023 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -23,7 +23,7 @@ dependencies { intellij { type.set("PS") - version.set("PS-2022.3.1") + version.set("PS-2023.3") plugins.set(listOf("com.jetbrains.php")) pluginName.set(properties("pluginName")) updateSinceUntilBuild.set(false) diff --git a/changelog.md b/changelog.md index 2bcc096..7bbfa7e 100644 --- a/changelog.md +++ b/changelog.md @@ -3,6 +3,10 @@ ## Unreleased ### Changed +- Remove entity type propagation on repository/collection/relationships in `find*`/`get*` and similar methods. This functionality is now built-in in PHPStorm as it supports enough of generics. +- Drop support for Orm v3. +- Fix missing support for like operator preventing reference detection in `findBy()` methods. +- Add support for resolving filtering expressions when relationship is defined by a generic `ManyHasMany`. ## 0.9.1 - 2023-07-28 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..d64cd49 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 84a0b92..1af9e09 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,99 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd3..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/kotlin/org/nextras/orm/intellij/completion/EntityPropertiesProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/completion/EntityPropertiesProvider.kt index a933e2c..71e55d5 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/completion/EntityPropertiesProvider.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/completion/EntityPropertiesProvider.kt @@ -36,17 +36,12 @@ class EntityPropertiesProvider { return } - val project = parameters.editor.project ?: return val fieldExpression = parameters.originalPosition!!.text val fieldExpressionLen = parameters.editor.caretModel.offset - parameters.originalPosition!!.textOffset val expression = fieldExpression.substring(0, fieldExpressionLen) - val isV3 = OrmUtils.isV3(project) - val (sourceCls, path) = OrmUtils.parsePathExpression(expression, isV3) - val classSuffix = when (isV3) { - true -> "->" - false -> "::" - } + val (sourceCls, path) = OrmUtils.parsePathExpression(expression) + val classSuffix = "::" val queriedEntities = OrmUtils.findQueriedEntities(context, sourceCls, path) queriedEntities @@ -81,14 +76,6 @@ class EntityPropertiesProvider { ) } - if (isV3 && path.size == 1 && sourceCls == null) { - result.addElement( - LookupElementBuilder.create("this->") - .withPresentableText("this") - .withIcon(PhpIcons.CLASS) - .withTypeText(cls.type.toString()) - ) - } if (path.size == 1 && sourceCls == null) result.addElement( LookupElementBuilder.create(cls.fqn + classSuffix) diff --git a/src/main/kotlin/org/nextras/orm/intellij/completion/ModifiersProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/completion/ModifiersProvider.kt index 5ef9dfe..4a5ed8e 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/completion/ModifiersProvider.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/completion/ModifiersProvider.kt @@ -5,7 +5,6 @@ import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.util.ProcessingContext -import org.nextras.orm.intellij.utils.OrmUtils class ModifiersProvider : CompletionProvider() { override fun addCompletions( @@ -13,23 +12,17 @@ class ModifiersProvider : CompletionProvider() { context: ProcessingContext, result: CompletionResultSet ) { - val isV3 = OrmUtils.isV3(params.editor.project ?: return) - result.addElement(LookupElementBuilder.create("enum").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("default").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("virtual").withInsertHandler(withoutParams)) - result.addElement(LookupElementBuilder.create("container").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("1:m").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("m:1").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("1:1").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("m:m").withInsertHandler(withParams)) result.addElement(LookupElementBuilder.create("primary").withInsertHandler(withoutParams)) result.addElement(LookupElementBuilder.create("primary-proxy").withInsertHandler(withoutParams)) - - if (!isV3) { - result.addElement(LookupElementBuilder.create("wrapper").withInsertHandler(withParams)) - result.addElement(LookupElementBuilder.create("embeddable").withInsertHandler(withoutParams)) - } + result.addElement(LookupElementBuilder.create("wrapper").withInsertHandler(withParams)) + result.addElement(LookupElementBuilder.create("embeddable").withInsertHandler(withoutParams)) } companion object { diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReference.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReference.kt index c08819b..8d81f7e 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReference.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReference.kt @@ -9,6 +9,10 @@ import com.jetbrains.php.lang.psi.elements.MethodReference import com.jetbrains.php.lang.psi.elements.StringLiteralExpression import org.nextras.orm.intellij.utils.OrmUtils +/** + * Makes property reference in methods like `$collection->findBy(['title' => 'value'])`. Supports traversing + * on the path. This makes it clickable to the property definition. + */ class CollectionPropertyReference constructor( element: StringLiteralExpression, private val methodReference: MethodReference, diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReferenceProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReferenceProvider.kt index 71b6eda..8ab0bd3 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReferenceProvider.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/CollectionPropertyReferenceProvider.kt @@ -5,25 +5,29 @@ import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceProvider import com.intellij.util.ProcessingContext import com.jetbrains.php.lang.parser.PhpElementTypes -import com.jetbrains.php.lang.psi.elements.* +import com.jetbrains.php.lang.psi.elements.ArrayCreationExpression +import com.jetbrains.php.lang.psi.elements.ArrayHashElement +import com.jetbrains.php.lang.psi.elements.MethodReference +import com.jetbrains.php.lang.psi.elements.ParameterList +import com.jetbrains.php.lang.psi.elements.PhpPsiElement +import com.jetbrains.php.lang.psi.elements.StringLiteralExpression import org.nextras.orm.intellij.utils.OrmUtils import java.util.regex.Pattern class CollectionPropertyReferenceProvider : PsiReferenceProvider() { - override fun getReferencesByElement(psiElement: PsiElement, processingContext: ProcessingContext): Array { + override fun getReferencesByElement( + psiElement: PsiElement, + processingContext: ProcessingContext + ): Array { val ref = getMethodReference(psiElement) ?: return emptyArray() val content = (psiElement as StringLiteralExpression).contents - val isV3 = OrmUtils.isV3(psiElement.project) - val matcher = when (isV3) { - true -> fieldExpressionV3.matcher(content) - false -> fieldExpressionV4.matcher(content) - } + val matcher = fieldExpression.matcher(content) if (!matcher.matches()) { return emptyArray() } - val (sourceCls, path) = OrmUtils.parsePathExpression(matcher.group(1), isV3) + val (sourceCls, path) = OrmUtils.parsePathExpression(matcher.group(1)) if (sourceCls == null && path.isEmpty()) { return emptyArray() } @@ -99,7 +103,6 @@ class CollectionPropertyReferenceProvider : PsiReferenceProvider() { } companion object { - private val fieldExpressionV3 = Pattern.compile("^([\\w\\\\]+(?:->\\w*)*)(!|!=|<=|>=|=|>|<)?$") - private val fieldExpressionV4 = Pattern.compile("^((?:[\\w\\\\]+::)?(\\w*)?(?:->\\w*)*)(!|!=|<=|>=|=|>|<)?$") + private val fieldExpression = Pattern.compile("^((?:[\\w\\\\]+::)?(\\w*)?(?:->\\w*)*)(!|!=|<=|>=|=|>|<|~)?$") } } diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyReference.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReference.kt similarity index 90% rename from src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyReference.kt rename to src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReference.kt index d6c48c2..a603bb7 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyReference.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReference.kt @@ -10,7 +10,7 @@ import com.jetbrains.php.lang.psi.elements.StringLiteralExpression import org.nextras.orm.intellij.utils.OrmUtils import org.nextras.orm.intellij.utils.PhpIndexUtils -class EntityPropertyReference(psiElement: StringLiteralExpression) : PsiPolyVariantReferenceBase(psiElement) { +class EntityPropertyNameReference(psiElement: StringLiteralExpression) : PsiPolyVariantReferenceBase(psiElement) { override fun multiResolve(b: Boolean): Array { val expr = element assert(expr.parent.parent != null) diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/PropertyNameReferenceProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReferenceProvider.kt similarity index 72% rename from src/main/kotlin/org/nextras/orm/intellij/reference/PropertyNameReferenceProvider.kt rename to src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReferenceProvider.kt index 11178b8..d7a1580 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/PropertyNameReferenceProvider.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/EntityPropertyNameReferenceProvider.kt @@ -7,14 +7,18 @@ import com.intellij.util.ProcessingContext import com.jetbrains.php.lang.psi.elements.MethodReference import com.jetbrains.php.lang.psi.elements.StringLiteralExpression -class PropertyNameReferenceProvider : PsiReferenceProvider() { +/** + * Makes property reference in methods like `$this->getProperty('title')`. + * This makes it clickable to the property definition. + */ +class EntityPropertyNameReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(el: PsiElement, processingContext: ProcessingContext): Array { assert(el is StringLiteralExpression) val method = el.parent?.parent as? MethodReference ?: return emptyArray() return when (method.name) { "setValue", "setReadOnlyValue", "getValue", "hasValue", "getProperty", "getRawProperty" -> { - arrayOf(EntityPropertyReference(el as StringLiteralExpression)) + arrayOf(EntityPropertyNameReference(el as StringLiteralExpression)) } else -> { emptyArray() diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/OrmReferenceContributor.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/OrmReferenceContributor.kt index dcd9293..1f01af5 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/OrmReferenceContributor.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/OrmReferenceContributor.kt @@ -17,7 +17,7 @@ class OrmReferenceContributor : PsiReferenceContributor() { ) psiReferenceRegistrar.registerReferenceProvider( PlatformPatterns.psiElement(PhpElementTypes.STRING), - PropertyNameReferenceProvider() + EntityPropertyNameReferenceProvider() ) psiReferenceRegistrar.registerReferenceProvider( PlatformPatterns.psiElement(PhpElementTypes.STRING), diff --git a/src/main/kotlin/org/nextras/orm/intellij/reference/ReferenceSearcher.kt b/src/main/kotlin/org/nextras/orm/intellij/reference/ReferenceSearcher.kt index 5650117..68ab315 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/reference/ReferenceSearcher.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/reference/ReferenceSearcher.kt @@ -13,7 +13,7 @@ import com.jetbrains.php.lang.psi.elements.StringLiteralExpression class ReferenceSearcher : QueryExecutorBase() { override fun processQuery(searchParameters: ReferencesSearch.SearchParameters, processor: Processor) { val property = searchParameters.elementToSearch as? PhpDocProperty ?: return - val providers = arrayOf(CollectionPropertyReferenceProvider(), PropertyNameReferenceProvider()) + val providers = arrayOf(CollectionPropertyReferenceProvider(), EntityPropertyNameReferenceProvider()) PsiSearchHelper.getInstance(property.project) .processElementsWithWord( diff --git a/src/main/kotlin/org/nextras/orm/intellij/typeProvider/CollectionTypeProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/typeProvider/CollectionTypeProvider.kt deleted file mode 100644 index 88cef02..0000000 --- a/src/main/kotlin/org/nextras/orm/intellij/typeProvider/CollectionTypeProvider.kt +++ /dev/null @@ -1,129 +0,0 @@ -package org.nextras.orm.intellij.typeProvider - -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiElement -import com.jetbrains.php.PhpIndex -import com.jetbrains.php.lang.psi.elements.FieldReference -import com.jetbrains.php.lang.psi.elements.MethodReference -import com.jetbrains.php.lang.psi.elements.PhpNamedElement -import com.jetbrains.php.lang.psi.elements.Variable -import com.jetbrains.php.lang.psi.resolve.types.PhpType -import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4 -import com.jetbrains.php.lang.psi.resolve.types.PhpTypeSignatureKey -import org.nextras.orm.intellij.utils.OrmUtils -import org.nextras.orm.intellij.utils.PhpIndexUtils - -class CollectionTypeProvider : PhpTypeProvider4 { - override fun getKey(): Char { - return '\u0241' - } - - override fun getType(element: PsiElement): PhpType? { - if (element !is MethodReference || element.classReference == null) { - return null - } - - val methodName = element.name - if (!allMethods.contains(methodName)) { - return null - } - - val isPluralMethod = pluralMethods.contains(methodName) - val arraySuffix = if (isPluralMethod) "[]" else "" - - val parent = element.classReference!! - when (parent) { - is MethodReference -> { - val type = PhpType() - parent.type.types - .filter { it.startsWith("#$key") } // we propagate further only our signature - .forEach { subType -> - if (!isPluralMethod) { - type.add(subType.removeSuffix("[]")) - } else { - type.add(subType) - } - } - if (type.isEmpty) { - parent.type.types.forEach { subType -> - type.add("#$key$subType") - } - } - return type - } - is FieldReference -> { - if (!parent.resolveLocalType().isEmpty) { - return PhpType().add("#$key${parent.signature}$arraySuffix") - } - // allowed type -> general processing - } - is Variable -> { - // allowed type -> general processing - } - else -> { - return null - } - } - - val type = PhpType() - parent.type.types - .forEach { subType -> - if (subType.startsWith("#$key")) { - if (!isPluralMethod) { - type.add(subType.removeSuffix("[]")) - } else { - type.add(subType) - } - } else { - type.add("#$key${subType.removeSuffix("[]")}$arraySuffix") - } - } - return type - } - - override fun complete(expression: String, project: Project): PhpType? { - return null - } - - override fun getBySignature(expression: String, visited: Set, depth: Int, project: Project): Collection? { - if (expression.endsWith("[]")) { - return null - } - - val index = PhpIndex.getInstance(project) - val classTypes = PhpIndexUtils.getByType(PhpType().add(expression), index) - if (classTypes.isEmpty()) { - return null - } - - // $orm->books->getById() - val repoClassesList = classTypes.filter { OrmUtils.OrmClass.REPOSITORY.`is`(it, index) } - if (repoClassesList.isNotEmpty()) { - return OrmUtils.findRepositoryEntities(repoClassesList); - } - - // $books->tags->toCollection()->getById() - val hasHasManyType = classTypes.any { OrmUtils.OrmClass.HAS_MANY.`is`(it, index) } - if (hasHasManyType && expression.startsWith("#")) { - val arrayElementType = PhpType().add(PhpTypeSignatureKey.ARRAY_ELEMENT.sign(expression)) - return PhpIndexUtils.getByType(arrayElementType, index, visited, depth) - } - - // $myCollection->getById() - val entityClassesList = classTypes.filter { OrmUtils.OrmClass.ENTITY.`is`(it, index) } - if (entityClassesList.isNotEmpty()) { - return entityClassesList - } - - return null - } - - companion object { - private val relationshipMethods = setOf("get", "toCollection") - private val collectionPluralMethods = setOf("findBy", "orderBy", "limitBy", "fetchAll", "findAll", "findById") - private val collectionSingularMethods = setOf("fetch", "getBy", "getById", "getByChecked", "getByIdChecked") - private val collectionMethods = collectionPluralMethods + collectionSingularMethods - private val pluralMethods = relationshipMethods + collectionPluralMethods - private val allMethods = relationshipMethods + collectionMethods - } -} diff --git a/src/main/kotlin/org/nextras/orm/intellij/typeProvider/PersistenceMethodsTypeProvider.kt b/src/main/kotlin/org/nextras/orm/intellij/typeProvider/PersistenceMethodsTypeProvider.kt deleted file mode 100644 index 7c84066..0000000 --- a/src/main/kotlin/org/nextras/orm/intellij/typeProvider/PersistenceMethodsTypeProvider.kt +++ /dev/null @@ -1,47 +0,0 @@ -package org.nextras.orm.intellij.typeProvider - -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiElement -import com.jetbrains.php.lang.psi.elements.MethodReference -import com.jetbrains.php.lang.psi.elements.PhpNamedElement -import com.jetbrains.php.lang.psi.elements.PhpTypedElement -import com.jetbrains.php.lang.psi.resolve.types.PhpType -import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4 - -class PersistenceMethodsTypeProvider : PhpTypeProvider4 { - override fun getKey(): Char { - return '\u0240' - } - - override fun getType(element: PsiElement): PhpType? { - if (element !is MethodReference) { - return null - } - if (element.name != "persist" && element.name != "persistAndFlush") { - return null - } - - //cannot access index here, so just dummy check - val className = element.classReference!!.name!!.lowercase() - if (!className.endsWith("model") && !className.endsWith("repository") && !className.endsWith("repositorycontainer")) { - return null - } - - if (element.parameters.isEmpty()) { - return null - } - - return when { - element.parameters[0] !is PhpTypedElement -> null - else -> (element.parameters[0] as PhpTypedElement).type - } - } - - override fun complete(expression: String, project: Project): PhpType? { - return null - } - - override fun getBySignature(expression: String, visited: Set, depth: Int, project: Project): Collection? { - return null - } -} diff --git a/src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt b/src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt index 008e8cc..c17bca7 100644 --- a/src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt +++ b/src/main/kotlin/org/nextras/orm/intellij/utils/OrmUtils.kt @@ -1,11 +1,15 @@ package org.nextras.orm.intellij.utils -import com.intellij.openapi.project.Project import com.jetbrains.php.PhpIndex import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty -import com.jetbrains.php.lang.psi.elements.* +import com.jetbrains.php.lang.psi.elements.ArrayCreationExpression +import com.jetbrains.php.lang.psi.elements.ClassConstantReference +import com.jetbrains.php.lang.psi.elements.GroupStatement +import com.jetbrains.php.lang.psi.elements.MemberReference +import com.jetbrains.php.lang.psi.elements.MethodReference +import com.jetbrains.php.lang.psi.elements.PhpClass +import com.jetbrains.php.lang.psi.elements.PhpReturn import com.jetbrains.php.lang.psi.resolve.types.PhpType -import java.util.* object OrmUtils { enum class OrmClass constructor(private val className: String) { @@ -26,19 +30,6 @@ object OrmUtils { } } - private var isV3: Boolean? = null - - fun isV3(project: Project): Boolean { - val index = PhpIndex.getInstance(project) - if (isV3 != null) { - return isV3!! - } - - val collectionFunction = index.getInterfacesByFQN("\\Nextras\\Orm\\Collection\\Functions\\IArrayFunction") - isV3 = collectionFunction.isEmpty() - return isV3!! - } - fun findRepositoryEntities(repositories: Collection): Collection { val entities = HashSet(1) for (repositoryClass in repositories) { @@ -53,7 +44,8 @@ object OrmUtils { continue } - val arr = (entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild as ArrayCreationExpression? + val arr = + (entityNamesMethod.lastChild as GroupStatement).firstPsiChild!!.firstPsiChild as ArrayCreationExpression? val phpIndex = PhpIndex.getInstance(repositoryClass.project) for (el in arr!!.children) { if (el.firstChild !is ClassConstantReference) { @@ -114,31 +106,22 @@ object OrmUtils { } } - fun parsePathExpression(expression: String, isV3: Boolean): Pair> { - if (isV3) { - val path = expression.split("->") - return when (path.size > 1) { - true -> Pair( - path.first(), - path.drop(1).toTypedArray() - ) - false -> Pair( - null, - path.toTypedArray() - ) - } - } else { - val delimiterPos = expression.indexOf("::") - val sourceClass = expression.substring(0, delimiterPos.coerceAtLeast(0)) - val path = if (delimiterPos == -1) expression else expression.substring((delimiterPos + 2).coerceAtMost(expression.length)) - return Pair( - sourceClass.ifEmpty { null }, - path.split("->").toTypedArray() - ) - } + fun parsePathExpression(expression: String): Pair> { + val delimiterPos = expression.indexOf("::") + val sourceClass = expression.substring(0, delimiterPos.coerceAtLeast(0)) + val path = + if (delimiterPos == -1) expression else expression.substring((delimiterPos + 2).coerceAtMost(expression.length)) + return Pair( + sourceClass.ifEmpty { null }, + path.split("->").toTypedArray() + ) } - private fun findTargetEntities(currentEntities: Collection, path: Array, pos: Int): Collection { + private fun findTargetEntities( + currentEntities: Collection, + path: Array, + pos: Int + ): Collection { if (path.size == pos + 1) { return currentEntities } @@ -152,6 +135,12 @@ object OrmUtils { private fun addEntitiesFromField(entities: MutableCollection, field: PhpDocProperty) { val index = PhpIndex.getInstance(field.project) + val candidateTypes = mutableListOf() + for (type in field.type.typesWithParametrisedParts) { + if (type.contains("Nextras\\Orm\\Relationship") && type.contains("<")) { + candidateTypes.add(type.dropWhile { it != '<' }.removePrefix("<").removeSuffix(">")) + } + } for (type in field.type.types) { if (type.contains("Nextras\\Orm\\Relationship")) { continue @@ -161,7 +150,10 @@ object OrmUtils { } else { type } - for (entityCls in PhpIndexUtils.getByType(PhpType().add(addType), index)) { + candidateTypes.add(addType) + } + for (candidateType in candidateTypes) { + for (entityCls in PhpIndexUtils.getByType(PhpType().add(candidateType), index)) { if (!OrmClass.ENTITY.`is`(entityCls, index) && !OrmClass.EMBEDDABLE.`is`(entityCls, index)) { continue } diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index b1e903e..bbfc20a 100644 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -41,11 +41,6 @@ level="WARNING"/> - - - - -