PhpStorm Code Style 'Space - Within - Brackets' not functioning - php

I am working on a PHP Laravel project with a team that requires spaces within brackets like this:
$t = $one[ 0 ];
I attempted to accomplish this by set the following requirement in the Code Style Preference:
The highlights show that spaces should be added within brackets as needed. However, after saving and restarting, I do not get this style applied, no matter how many time I press Ctrl+Alt+L.
Worse still, PhpStorm strips out the spaces that already exist within brackets, which causes a huge headache when I try to auto format existing code.
So this:
Is reformatted and becomes this:
I've set up other custom code style setting, and the other custom setting are getting applied.
Could someone offer some help with fixing this style problem?

That option works just fine. It is for accessing individual array elements (e.g. $t = $one[ 0 ];).
But on your screenshots, where it does not work... it's array initializer (in other words, $var = array('aaa', 'bbb');)... and for that you need to use appropriate option -- "Array initializer parentheses" (which is just a bit below of what you have tried above).

Related

How do I disable IntelliSense in comments in Visual Studio Code?

I'm using Visual Studio Code, mostly to work with PHP. Everytime I hit ., IntelliSense kicks in and offers me PHP globals and functions, starting with $_COOKIE. I usually know what global or function I want, so it's a bit annoying. This even happens when I'm within a comment block (/* ... */ or // ...), which is far more annoying. Most of my time is spent going back and deleting $_COOKIE.
An example (not PHP, but you get the idea):
I've tried disabling it as suggested in the docs:
// Controls if quick suggestions should show up while typing
"editor.quickSuggestions": false,
// Controls if suggestions should be accepted with "Enter" - in addition to "Tab". Helps to avoid ambiguity between inserting new lines and accepting suggestions.
"editor.acceptSuggestionOnEnter": true,
// Controls the delay in ms after which quick suggestions will show up.
"editor.quickSuggestionsDelay": 10000,
// Enable word based suggestions
"editor.wordBasedSuggestions": true
... but this has absolutely no effect whatsoever. I still get the list when I hit the dot. The delay increase from 100 to 1000, too, has no effect.
How do I turn off IntelliSense inside code comments?
How do I disable IntelliSense on hitting . and just have it show up when I hit Ctrl+Space? (See update 2 below)
How do I disable IntelliSense completely, at least for PHP?
Update: As mentioned here, disabling quick suggestions on trigger characters is achieved via:
// Controls if suggestions should automatically show up when typing trigger characters
"editor.suggestOnTriggerCharacters": false
However, the other options mentioned above still don't do anything.
Update 2: It is possible to mess with the . binding by adding this to the keybindings.json file:
{
"key": ".",
"command": "x",
}
However,this results in a warning message at the top of the screen that says "command 'x' not found". If you leave it empty or try to pass null to command, it still doesn't work, as it doesn't overwrite the default key binding. According to the documentation, it's possible to disable a certain action by prefixing it with a -, but this doesn't work for me:
"command": "-^acceptSelectedSuggestion"
or
"command": "-acceptSelectedSuggestion"
In either case, acceptSelectedSuggesdtion isn't really the command that's being executed when I hit ., it's probably more like:
"command": "-editor.action.triggerSuggest"
But this doesn't work either.
Since about March or April 2017, this has been fixed, and also the default has changed to be no auto-complete in comments. The default is:
"editor.quickSuggestions": {
"other": true,
"comments": false,
"strings": false
},
I don't have that explicitly in my settings, and just did a test with a fresh PHP file, and I can type global. then space, and don't get anything auto-completed. (I tried both main code and in comments.) I do see $COOKIE pop up as the first suggestion, but I need to use up/down arrows and then enter to bring it in.
Aha, global. then ENTER does give me global.$COOKIE (even in comments, which is a bit weird). I can fix that with:
"editor.acceptSuggestionOnEnter": "off",
To see other settings you might want to touch, go to the settings page and type "suggestion" in the search box. Each is commented. E.g. "editor.suggestOnTriggerCharacters": false, gets rid of the auto-suggestions completely.
You can also specify the settings for just one language, e.g.
"[php]": {
"editor.suggestOnTriggerCharacters": false,
},
Despite Darren Cook's answer and the docs, the editor.quickSuggestions settings don't do anything for suggestions that pop up due to trigger characters (see this issue on GitHub). These seem to be subject to their own rules. Namely, when typing a trigger character in a string, you never get the suggestions, no matter what you said in editor.quickSuggestions; and when typing a trigger character in a comment or "other", you always get the suggestions, no matter what you said in editor.quickSuggestions.
Thus the only reliable way to get rid of what I'm calling "trigger-character suggestions" (which are by far the most annoying kind!) is to use the setting specifically devoted to it:
"editor.suggestOnTriggerCharacters": false
If someone can leave a comment on how to discover what the trigger characters are, or better yet, how to specify them, I would be all too happy to edit my answer to take this into account.
Note that the suggestions which pop up due to actually matching the characters you type with known modules, variables, functions, etc., are still controlled by editor.quickSuggestions and not by editor.suggestOnTriggerCharacters.

Zend Studio / Eclipse formatting new line on end parenthesis of function invocation

So, this is how function invocations are setup with my custom formatting:
Eclipse does this regardless, notice at the end the 3 parentheses, together. arg?
$this->addElement(
new Form_Element_Note('test',
array(
'value' => 'test'
)));
I want to figure this out in the formatter, but I literally see nothing aside from chaining method invocations that could accomplish this style of formatting:
$this->addElement(
new Form_Element_Note(
'test',
array(
'value' => 'test'
)
)
);
Notice this applies to object and function invocations. Any ideas how to edit this manually? I couldn't find anything in the documentation that could do this, but it would surely seem like something possible..
I have the same problem. Using a own (no-psr) coding style in eclipse is really difficult. After many tries I finally made it to format array brackets [] and () in new lines. But it's not a very nice solution.
First Open the formatter and edit your profile, then go to:
New Lines > Array Initializers > Insert new line before closing parenthesis of array initializer
Line Wrapping > Expressions > Array initializer > Force Split
Cons:
Every array gets splitted now, even if it has just one entry
if you use an array as method parameter the ending round brace won't be in a new line
Another huge Problem of code formatting in eclipse is (maybe just me). If you execute the formating mutliple times, it looks different. At least for on Save usage it is big problem.
I stopped trying to use code formating in eclipse since it isn't implemented very good and a way to static. I'd be glad, if anybody could provide us help (or implement an "Insert new line before closing parenthesis" for method calls)
Using Mars.2 Release (4.5.2) for PHP Developers.

Find where a variable is defined in PHP (And/or SMARTY)?

I'm currently working on a very large project, and am under a lot of pressure to finish it soon, and I'm having a serious problem. The programmer who wrote this last defined variables in a very odd way - the config variables aren't all in the same file, they're spread out across the entire project of over 500 files and 100k+ lines of code, and I'm having a hell of a time figuring out where a certain variable is, so I can fix an issue.
Is there a way to track this variable down? I believe he's using SMARTY (Which I can not stand, due to issues like this), and the variable is a template variable. I'm fairly sure that the variable I'm looking for was initially defined as a PHP variable, then that variable is passed into SMARTY, so I'd like to track down the PHP one, however if that's impossible - how can I track down where he defined the variable for SMARTY?
P.S. I'm in Vista, and don't have ssh access to the server, so 'grep' is out of the question.
Brute force way, because sometimes smarty variables are not directly assigned, but their names can be stored in variables, concatenated from many strings or be result of some functions, that makes it impossible to find in files by simply searching / greping.
Firstly, write your own function to print readable backtrace, ie:
function print_backtrace()
{
$backtrace = debug_backtrace(FALSE);
foreach($backtrace as $trace)
echo "{$trace['file']} :: {$trace['line']}<br>";
}
Open main smarty file (Smarty.class.php by default) and around line 580 there is function called assign. Modify it to watch for desired variable name:
function assign($tpl_var, $value = null)
{
if($tpl_var == 'FOOBAR') /* Searching for FOOBAR */
{
print_backtrace();
exit;
}
The same modification may be required for second function - assign_by_ref. Now after running script you should have output like that:
D:\www\test_proj\libs\smarty\Smarty.class.php :: 584
D:\www\test_proj\classes.php :: 11
D:\www\test_proj\classes.php :: 6
D:\www\test_proj\functions.php :: 7
D:\www\test_proj\index.php :: 100
Second line points to the place where variable was first assigned.
This sort of thing is the #1 reason I install Cygwin on all my windows machines.
grep myvariablename `find project_dir -name "*.php"`
I can't imagine programming without a working grep.
There is an interesting further option, ugly like hell but helpful if you are really lost.
If you would like to know where THE_NAME was defined, write lines like these on a place you are sure is run first:
error_reporting(E_ALL);
define('THE_NAME', 'Chuck Norris');
If later PHP will run the definition you are looking for, it will write a notice like this:
Notice: Constant THE_NAME already defined
in /home/there/can-rip-a-page-out-of-facebook.com/SomeConfiguration.php on line 89
Then you know that the definition you are looking for is in the file SomeConfiguration.php on line 89.
To have this working, you must consider
if there are HTTP forwards in the framework on the way to the code you set in
if there are further commands setting the PHP error reporting mode
So sometimes it helps to add some exit('here') in order not to blur the output. Maybe you have to narrow down a bit or you have to set error_reporting earlier, but you'll find it.
It's not a perfect solution, but I find agent ransack useful for searching large directories and files. Might help you narrow things down. The search results will allow you to read the exact line it finds a match on in the result pane.
If you use the netbeans editor just "right click" -> "go to Definition"
Or ctrl + click on the variable.
If the editor can't figure it out, you could fallback to the "Find in files" option.
Just use one of the available PHP IDEs (or a simple text editor like Notepad++ if you're really desperate) and search for the name of the variable in all source files (most PHP IDEs also support finding where functions/vars were defined and allow you to jump to the relevant piece of code). Though it seems weird that you don't know what piece of code calls the template (whether it's Smarty or anything else doesn't really matter). You should be able to drill down in the code starting from the URI (using any IDE which supports debugging), because that way you're bound to see where said variable is defined.

Echoing variable construct instead of content

I'm merging two different versions of a translations array. The more recent version has a lot of changes, over several thousand lines of code.
To do this, I loaded and evaluated the new file (which uses the same structure and key names), then loaded and evaluated the older version, overwriting the new untranslated values in the array with the values we already have translated.
So far so good!
However, I want to be able to echo out the constructor for this new merged array so I can cut and paste it into the new translation file, and have job done (apart from completing the rest of the translations..).
The code looks like this (lots of different keys, not just index):
$lang["index"]["chart1_label1"] = "Subscribed";
$lang["index"]["chart1_label2"] = "Unsubscribed";
And the old..
$lang["index"]["chart1_label1"] = "Subscrito";
$lang["index"]["chart1_label2"] = "Não subscrito";
After loading the two files, I end up with a merged $lang array, which I then want to echo out in the same form, so it can be used by the project.
However, when I do something like this..
foreach ($lang as $key => $value) {
if (is_array($value)) {
foreach ($value as $key2 => $value2) {
echo "$lang['".$key."']"; // ... etc etc
}
}
}
..obviously I get "ArrayIndex" etc etc instead of "$lang". How to echo out $lang without it being evaluated..? Once this is working, can add in the rest of the brackets etc (I realise they are missing), but just want to make this part work first.
If there's a better way to do this, all ears too!
Thanks.
edit:
What I was really looking for was this:
"Note: Unlike the three other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings."
So no need even to escape. May come in handy one day for someone... about merging the arrays, there's a great recursive array merging function on the PHP manual page for array_merge(), which also came in handy.
Thanks to whoever downvoted! Love you too.
Either escape the $: "\$lang" or use single quotes: '$lang'
Note that you really don't need to post a whole page of backstory, if your entire question just boils down to "how do I output a dollar sign in PHP"
there is var_export() function, but I do not understand the purpose of this terrible mess.
It's all too... manual
why not to use a gettext - an industry standard for multi-language site?
or at least some other format, more reliable than plain PHP one?
Programming code is not intended to be written automatically.

How do I examine defined constants in PHP?

I'm stepping through the source code of CodeIgniter with Xdebug in NetBeans and I'm looking for a way to see defined constants as they are defined. If it's not possible, are there any other ways to display all defined constants?
Take a look at the get_defined_constants function. It will return an array of all the defined constants in the code up to the point of the function call. You can then use print_r to print out the array.
This kind of practice I use is quite decent as it shows only custom/user created constants.
print_r(var_export(get_defined_constants(true)['user'], true));
Wrap this within pre tags or just view source and you'll get very nice array of all the stuff You defined.
Note that this is not going to work with php 5.3.* where in 5.4.* it outputs fine.
In earlier versions of php, get_defined_constants() must be assigned to a variable first, before output.
Something like this.
$gdc = get_defined_constants(true);
print_r( var_export($gdc['user'], true) );
You probably want to adapt:
$arr = get_defined_vars();
The best I could find is to press F7 (step into) while in debug mode to have your constant line executed.
define('SOME_CONSTANT','VALUE');
And then double click "SOME_CONSTANT", right click and chose add new watch (shortcut: shift + ctrl + F7), and the add new watch window will appear with the constant prepopulated, select enter and you should see your constant value in the Variables (if you have the blue diamond selected "Show watches inside variables view") & Watches window panel.
Also quite handy to know, you can hover over variables to see their value as opposed to looking in the Debugging > Variables window panel...just need to turn it on as it's off by default...apparently buggy...using the latest xdebug and it's been fine for me so far.
Tools > Options > PHP > General Tab > Debugging Section > Check Watches and Balloon evaluation
Hopefully this will still be useful 2 years later.

Categories