Undefined class if class is in different namespace - phpstorm

I have a yii2 project set up on phpstorm 8.0.3. My namespace structure is as follows:
backend\
controllers
models
...
frontend\
controllers
models
..
common\
controllers
models
I used composer on the project and have various dependancies installed in the vendor folder.
Whenever I try to use a class that is not in the same base namespace (frontend, backend or common), I get an undefined class error. The odd thing is the namespace of the class is in autocomplete:
Another oddity is that the undefined class error disappears for some classes if the file with the defined class is opened.

It looks like the PHPStorm cache was somehow corrupted. I ended up invalidating the cache by going to File -> Invalidate Caches/Restart. This deleted my history but fixed the undefined class issue.

You must declare in use section nedded class or namespace. For example, if you need to use BaseController from custom\controllers namespace:
<?php
namespace frontend\components;
// Add this line
use common\controllers\BaseController;
class Controller extends BaseController {
}

I had to reset my PHPstorm to fix the issue of "Class not found".
File > Manage IDE Settings > Restore Default Settings...
Be carreful, it rests everything, but it also offers you to back up your current settings. After that, all has been hard reseted and it now works again.

Can be helpful sometimes.
Settings -> Directories
Remove folders from "Excluded"

I think you have some problems with composer autoload.
Try :
composer update

This was happening to me because of my PHP language settings. I found this out by taking out the namespace in one of my classes. The error changed to "Scalar types are only available in PHP 7".
Go to File -> Settings -> Language & Frameworks -> PHP. Change the PHP language level to language version 7 or greater.
Edit:
After doing that, Insert -> Getters and Setters was intermittently generating functions and comments as mixed instead of string. I don't know why this happened but I recreated all my fields manually and that fixed the issue.

Related

ViewHelper is not found

I fiddled around with it for more than 8 hours without getting it resolved.
All I want is to call a ViewHelper in a Fluid template. I did that before and I never had a similar problem.
My ViewHelper file is located in
EXTDIR/VendorName/Classes/ViewHelpers/SomeViewHelper.php.
In my Fluid Template I use the namespace
{namespace k=VendorName\Extname\ViewHelpers}.
Somewhere in the template I call the ViewHelper with
{k:some()}.
The ViewHelper script "SomeViewHelper.php" contains the following code:
class SomeViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {
public function initializeArguments() { }
public function render() {
return 7;
}
}
As you can see, the whole thing is quite simple and the expected output on the page should be "7". But calling a page in the frontend produces this error message:
Oops, an error occurred!
Could not analyse class:VendorName\Extname\ViewHelpers\SomeViewHelper maybe not loaded
or no autoloader?"
Any hints on what might be wrong here?
Cheers
Michael
If everything is spelled correct, and even after deleting System/Configuration Cache the ViewHelper doesn't come up (Could not analyse.. / maybe not loaded or no autoloader), try to reinstall the extension in extension manager!
Your path to the viewHelper source file is wrong.
The correct path should be (without vendorname):
EXTDIR/Classes/ViewHelpers/SomeViewHelper.php
You also need to make sure, you use the correct namespace for your viewHelper (if you're on TYPO3 6+, don't use the old Tx_ classes but namespaces).
<?php
namespace VendorName\Extname\ViewHelpers;
class SomeViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
public function initializeArguments() { }
public function render() {
return 7;
}
}
The error message seems to indicate that the class is not found.
Without more info, I would probably suspect a typo somewhere (pun not intended).
The following assumes you are using TYPO3 7 and not composer mode:
First, please check if your viewhelper class is autoloaded. This will help to narrow down the problem. On the command line in the htdocs directory: grep SomeViewHelper typo3temp/autoload/autoload_classmap.php This should give you a hit, if the ViewHelper class is included in the autoload file.
If the classes are not autoloaded, you might manually want to do the autoloading: On the command line in the htdocs directory: php typo3/cli_dispatch.phpsh extbase extension:dumpclassloadinginformation
For more information see: https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Autoloading/Index.html. For more in depth info see this: http://insight.helhum.io/post/130876393595/how-to-configure-class-loading-for-extensions-in You can find this functionality of autoloading in the install tool in TYPO3 8, so in that case you would not need to run the command on the command line.
If this does not work either, check the following:
Are you using namespace correctly in the class: <?php namespace VendorName\Extname\ViewHelpers\SomeViewHelper;
Is the path (including Camelcase class name) correct: /Classes/ViewHelpers/SomeViewHelper.php
After that, clear the system cache and reinitiate the autoloading as described above.
In order for the autoloading to be initiated automatically, you might have to update your ext_emconf.php (if you are not using composer mode) or composer.json (if you are using composer mode).
Just some questions:
Did you add the TypoScript Template of the Extension to the Static Includes?
If you're using a unix-alike system, are you sure that your webserver has the permission to read that files?
If TYPO3 is installed in composer mode and your extension is not installed via composer (e.g. a ProviderExtension of FluidTYPO3), you must provide autoload information for your extension in the main composer.json file, as described within TYPO3-composer-documentation:
In Composer Mode all class loading information must be provided by each of the installed extensions or the root package. If TYPO3 extensions are not installed by composer, e.g. because they are directly committed to the root package or a new package is kickstarted, class loading information needs to be provided, otherwise no classes can be loaded for these extensions/ packages.
E.g. if you have a site extension directly committed to your root package, you must include the class loading information in the root package like that:
Drove me crazy to get my ViewHelpers autoloaded. Providing the autoload-information within a composer.json or the ext_emconf.php of the extension and reinstalling it didn't do the trick.

multiple definitions exist for class

I'm using Kohana framework which allows for multiple class definitions (in application and system subfolders). I'm using phpstorm as an IDE which gives me messages multiple definitions exist for class . Is there any way to tell phpStorm which class definition is correct?
Is there any way to tell PhpStorm which class definition is correct?
You cannot, unfortunately.
https://youtrack.jetbrains.com/issue/WI-17646 -- watch this ticket (star/vote/comment) to get notified on any progress.
ATM you either just ignore the under-waving .. or you can configure that inspection to not to report such cases (Settings/Preferences | Editor | Inspections | PHP | Undefined | Undefined class, it has Don't report multiple class declaration potential problems checkbox).
Even with that inspection configured, IDE will still ask you what class declaration to jump to (and this is correct behaviour as IDE does not know if you want to see the original implementation or implement your own).
The only other way is to ensure that there is only one class with the same name in the project. For that you may use:
Mark whole folder as excluded
Mark individual file as Plain Text
Both are available via content menu in Project View and applicable to project files only (e.g. will be unavailable or will do nothing useful if tried to apply in Library scope).
You should just ignore the complete cache folder.
Go to Settings > Directories
Choose var\cache
Set it to 'Excluded'
From: https://github.com/Haehnchen/idea-php-symfony2-plugin/issues/301
I've found a possible solution to my problem - I can mark file as plain
As variant you can turn off inspection only for specific class. Put cursor inside underwaved class name, then Alt+Enter → Inspection options → Supress for statement
PHPStorm adds
/** #noinspection PhpUndefinedClassInspection */
above class declaration and class name is not underwaved anymore.
I've been around the web everywhere and not a single option worked for me... I've been struggling for months with it, and today I found a solution, so if none of the above works for you, try redefining the PHP Include Path List. under Settings > Languages & Frameworks > PHP, make sure only the folders containing paths to source used by your project or application is configured.
My scenario is that I do a lot of package development, and while my packages are all in one project, they are also "symlinked" in "vendor" in my composer configuration, so there is duplicated code found by PHPStorm, in the vendor folder and my packages folder. Similarly, if include paths are duplicated, or paths are configured to find code outside of your project, which is already part of the project, it will also find multiple definitions. So, excluding the symlinked folders in vendor, allows PHPStorm to only find one copy of the source to my packages, and if my packages contain vendor folders of their own, they will also show up as duplicated definitions. Remove anything in the Include Path list where it may find dipplication
Just some addition to the Andy White's comment:
Settings | Editor | Inspections | PHP | Undefined | Undefined class | Don't report multiple class declaration potential problems
I really couldn't find this config and thought it was no there now, but this is still there, but very well hidden)
It is a little counterintuitive and inconspicuous, but the needed checkbox is in the right panel, and appears only if you click on the Undefined class row:
Prolog
Guess there are several ways to solve this problem. Actually, it's just a warning and it says that phpstorm can't provide you with autocompletion so you have to work a bit harder :D
I had the same problem as many others here and solved it by ignoring unwanted.
Scenario
Had a git project with a vendor-folder after composer install. Also, there is a my-project.phar in this project that also contains some vendor stuff and this caused my warnings.
Solution
File > Preferences|Settings > Directories
There you have to possibility to exclude files and folders. In my case it's the .phar so it's a "file" and you can add it at the bottom of the settings-window.
PHPStorm will no longer see duplicates.
This is very project-specific and I guess most people have to find their own solution but pointing to this may help to find the problem easier.
Hope this helps someone :)
Somewhere in your project there are multiple definitions for the same class. I discovered I had backup copies in my project which caused this warning. I removed the backups from my Project (a good idea anyway) and it fixed the error.
I don't know how you created the other definition, but if you or anyone has this issue due to calling class_alias(), then you can solve this issue quickly.
Consider
class_alias(
'The\AliasClass',
'My\RealClass',
true
);
and
class_alias(
'The\AliasClass',
'My\Real'.'Class', // <-- break up the string
true
);
With the latter, PhpStorm will not pick up the My\RealClass and your "multiple definition" warning will cease. This is an ancient JavaScript trick to embed HTML in a string literal, by the way.
This warning has annoyed me for a long time. I believe the answers here saying there is a duplicate file somewhere is correct. The reason I am getting the warnings are due to the autocomplete file to give phpStorm a hint on how to find codeIgniter functions. If you are doing this also that is the reason for some of the warnings. The autocomplete file makes phpStorm think there are two different definitions. However, I like autocomplete more than I dislike the warnings so I guess I have to live with them.
This is the autocomplete I'm referring to:
IntelliJ IDEA 12 not finding CodeIgniter classes, throwing errors
Alternatives that work after a fashion, but aren't so good
marking the file B you don't want to be used by autocomplete as "plain" or excluded, leaving file A active: this will disable notifications in the file C, but will also make autocompletion no longer work for whatever is in file B. So if somewhere else you use something that's rightly in B, and maybe there you want to exclude A from autocompletion, you can't do that.
disable the inspection: this will also disable undefined class warnings, so if I make any typos in any class name, I'll only discover this after deployment (or from the fact that autocomplete stops working for that object).
"Don't report multiple class declaration potential problems" - this is very nearly good, but I don't like having "potential problems" ignored; what if I create a class with an unwittingly duplicated name that is in use somewhere else? Granted that I'll catch it (or phpunit will), but still.
The best I've found so far
The way to go for now, at least until a more focused configuration is available for PHPStorm (e.g. "Alternative Classes"), is to mark those notifications - and only those - as ignorable:
/* #noinspection PhpUndefinedClassInspection */
/**
* Verify an existing contract. Requires agent and supervisor.
*
* #param array $data
* #param Cliente $cli
* #param User $age
* #param User $sup
* #return Contratto
*/
private function contratto(
array $data,
/* #noinspection PhpUndefinedClassInspection */
Cliente $cli,
/* #noinspection PhpUndefinedClassInspection */
User $age,
/* #noinspection PhpUndefinedClassInspection */
User $sup
) {
Note that to disable notifications in the PHPDoc comment I had to add a directive before the comment; this did not disable the notifications for the three parameters.
In the future, I wish to be able to specify those in PHPStorm as
* #param array $data raw data for the contract
* #param \local\foobar\Cliente $cli customer opening the contract
private function contratto(
array $data,
/*\local\foobar\*/Cliente $cli,
or better still, explicitly use a new PHPdoc tag such as "#replaces". So PHPStorm would know that my class is the one not replaced. I'll also have to decorate my use's to specify the class I'll be actually using.
And run a search for "#noinspection PhpUndefinedClassInspection" throughout my code.
Another way
The above problems stem from the fact that I have a "master" Customer class which is overridden by a "local" modification for the foobar client, whose Customers have (say) a special method.
The "correct" way of doing this should be to declare a FoobarCustomer which is only employed by foobar's code, and is a child class of Customer. Of course this is only possible if the child class is in my code, not in the framework's, and also I may need some methods in the parent class to be protected rather than private, which may make this solution either impossible or needful of Reflection:
/**
* Verify an existing contract. Requires agent and supervisor.
*
* #param array $data
* #param FoobarCliente $cli
* #param FoobarUser $age
* #param FoobarUser $sup
* #return Contratto
*/
private function contratto(array $data, FoobarCliente $cli, FoobarUser $age...
I had similar problem and it was quite annoying one. I was using Yii2 framework and as it turned out at the end I have accidentally created en extra "vendor" folder and composer.json in the root of the project (not in the root of the app) so I ended up with that warning as phpStorm was confused which extension folder is the right one.
I've deleted extra vendor folder and it solved the problem.
Try delete duplicate declared libraries
Settings -> Languages & Frameworks -> PHP -> Include Path
I resolved this in my case by removing a more specific entry in my composer.json that included code by another more general entry

Make YARD ignore certain class extensions

I am getting several warnings when generating my project documentation because YARD cannot parse some external class extensions
[warn]: in YARD::Handlers::Ruby::MixinHandler: Undocumentable mixin: YARD::Parser::UndocumentableError for class MyClass
[warn]: in file 'lib/Project/myclass.rb':7:
7: include Virtus.model
The root of the problem is one class extension that cannot be parsed. I know I could just run yard -q to suppress all warnings, but I would rather supress individual extensions than everything.
As far as I can see in the help, I could --exclude but right now, the offending class is part of an external gem. I also tried #!parse without success
class MyClass
# #!parse Virtus.model
include Virtus.model
end
I had the same problem, and I was able to hide the warning by obfuscating the inclusion so YARD cannot detect it:
class MyClass
send :include, Virtus.model
end
There is more discussion of this issue on github:
https://github.com/lsegal/yard/issues/546

ReSharper: Namespace does not correspond to file location

I renamed a folder and updated my namespace declarations, but ReSharper 6 claims that the namespace should be a reflection of how it was before the rename. Where is it storing the file location data?
Check to make sure your assembly name matches your new namespace. If you've changed your folder structure to match your new namespace, you may still see the ReSharper alert until you update the project properties.
As delliottg's comment says, in Visual Studio, go to
Project > [project name] Properties > Application
and change "Assembly name" as well as "Default namespace".
I also had this problem with a folder/namespace and none of the above steps fixed it.
In my case I had to do this in Visual Studio:
Right-click the "problem" folder in the solution explorer to open the properties
Ensure the "Namespace Provider" is set to true
This fixed the ReSharper issue for me and I was able to adjust namespaces as normal.
Root namespace is needed to be changed as following.
I use Resharper 2019.3.2 in VS 2019 vs 16.5.2 and I had similar issues.
When developing, I first work out my namespace hierarchy in a single project, then split the project in seperate class libraries. In the first stage, it is convenient to always let the subdirectory correspond to the namespace.
For example, my prototype MeshTools.dll project currently contains:
Meshtools ........................ 3 cs-files in \MeshTools
MeshTools.HeightField .......... 2 cs-files in \MeshTools\HeightField
MeshTools.VectorTools .......... 3 cs-files in \MeshTools\VectorTools
The above answers all assume one single namespace per project. Renaming directories manually may confuse Resharper and that can be repaired by setting the default assembly in the .csproj file to the proper namespace. Thanks for the tip.
However in my case, I have several namespaces in a single project, with each namespace in a Solution directory corresponding to a real directory. Setting the default assembly "Meshtools" does not affect ReSharper behaviour for HeightField and VectorTools, when things have gone wrong with the renaming.
I googled this issue and came by https://www.jetbrains.com/help/resharper/Refactorings__Adjust_Namespaces.html#
It turns out there is a right-click option on a Solution Directory -> Properties. You will find an option to decide, if the Solution Directory is a NameSpace provider or not. When something has gone wrong, Visual studio will reset the field to False. Set it back to True and Resharper will correctly refactor namespace or file location when needed..
If you're using JetBrains Rider, go to the Solution Explorer and right click on the csproj file, then properties in the context menu. In my case the Assembly Name was already updated but "Root Namespace" wasn't, updating Root Namespace allowed JetBrains to automatically update all namespaces.

How can I set the Root Namespace property correctly in a C++/CLI application?

I have a C++/CLI application in Visual Studio 2008 whose namespace follows the .NET guideline of CompanyName.TechnologyName[.Feature][.Design]. The problem is that there seems to be no way to set a multi-level namespace in the project's Root Namespace property. I have tried both CompanyName.TechnologyName and CompanyName::TechnologyName.
It seems that I cannot have a Form control inside a namespace that is not the root namespace as this causes the resources it uses to not be found, thus to me it seems impossible to follow their guideline and be consistent with my C# applications.
Is there a way to set this property to use multi-leveled namespaces or am I forced to use a root namespace that is simply one-level? Or is there a solution that I am overlooking?
Edit:
Functionality is added in Visual Studio 2010 to allow multi-level root namespaces. Use CompanyName.TechnologyName format NOT CompanyName::TechnologyName. While the latter works for /creating/ forms, if your forms require resources then when compiling, Visual Studio tries to save to CompanyName::TechnologyName.resources which will throw an error.
Not sure I see the resource problem. There is no notion of a "root namespace". You have the follow the C++ rules for namespace declarations, you'll have to nest them one at a time. For example:
namespace Contoso {
namespace Accounting {
namespace PayRoll {
namespace Employees {
// class declarations go here
}}}} // yeah, that sux
And in the .cpp file:
using namespace Contoso::Accounting::PayRoll::Employees;
There's no trouble adding resources when it is declared like this that I could find. But don't add a resource, then change the namespace name. The C++ IDE has no refactoring support whatsoever. Windows Forms development in C++/CLI isn't very popular, this would perhaps be one reason.