I'm looking for a indent application to fix all aspects of PHP code formatting - convert spaces, perform indentation in PHP and HTML code, leave HEREDOC alone, etc.
Please recommend a decent indenter for PHP.
find . -name '*.php' -printf "echo -e \"G=gg\n:wq\n\" | vim %p\n" | sh
I have found few things. First, the best way to mass-edit files is to use bash scripting and vim.
Second, vim indentation is not perfect and is not working always. So I had to rather do "=G" manually then review the source.
Finally, vim's command "retab" in collaboration with tab settings is great if only looking to change white-spaces into tabs.
I'd like to also point towards an awesome podcasts where I learned more about Vim:
http://vimcasts.org/episodes/show-invisibles/
http://vimcasts.org/episodes/tabs-and-spaces/
http://vimcasts.org/episodes/whitespace-preferences-and-filetypes/
http://vimcasts.org/episodes/tidying-whitespace/
Squizlabs has develop PHP_CodeSniffer, which tokenizes PHP, JavaScript and CSS files to detect and fix violations of a defined set of coding standards. It have phpcbf cli, that ensures your code remains clean and consistent. By their definition it should satisfied your need. Consider read their wiki, for further step.
2018 answer
Since originally finding solution, I've moved on to use https://styleci.io/. I am not affiliated with them, but I really like the simplicity and it keeps the project nice and tidy. Doesn't cost anything for my open-source project either.
I'd recomment PHPStorm, its not a command-line per se, but it does allow to specify custom code formatting and apply it to multiple files
Related
Is there any way to minify (or remove comments) in PHP using Visual Studio 2015? I use PHP Tools and when i release php scripts to public server, i would like at least remove all comments from code. I know, is there way to remove comments with content menu, but i wish to have comments in my project and no comments (or minimal and unread code) in publish scripts (some like Bundler & Minifier tool, but for php). Thanks
There is basically no point in minifying Php since there is no performance gain in doing so. Although if you insist, there are a few ways to remove comments/whitespaces from source. (and these are not limited to just VisualStudio) -
Use Gulp.
Use Command line options: php -w file.php => generates file without comments & whitespaces. Equivalent to php_strip_whitespace()
Use Regular Expression in Find-Replace Function of your IDE. You can use the following inside Find FieldBox. (and keep Replace fieldbox empty)
//.* or /.
Use a Library/tool like Php-Minify
Hope that helps!
Why aren't you going to use online tool to do it?
There are many online tools you can use instead of VS 2015.
Here is one tool for you.
http://beta.phpformatter.com/
Hope it helps you and check this answer as solved if it helps you.
Thanks!
You can check Comment Remover tool to remove all the comments from a file with a single button click. It also remove #regions and preserve XML Doc comments.
I think there is no tool for visual studio to do this. But you may use external tools to do the job. It's a common task to do this in build system like jenkins. The build system e. g. is able to react on many version control events.
But I also think that you want to make php code unreadable (like compiling). There are only a few options to hide your php code to other people. You could use ionCube for encrypting php files. But then you have to make sure, that the ionCube extension is also installed on the public web server. Also, ionCube is currently not available for php 7.2, only up to 7.1. Another option is to compile php code using HipHop, a PHP to C++ compiler engine: https://de.wikipedia.org/wiki/HipHop
I'm going to be doing some PHP editing for my job this summer, and am looking for an effective Emacs setup for editing it. I'm already heavily invested in Emacs, so switching to another editor is not worthwhile.
Right now, I have nXhtml-mode, which provides a PHP mode with syntax highlighting (there are at least three different ones in the wild) as well as MuMaMo for editing PHP embedded in HTML. I just started using Auto-Complete and Anything for programming and general Emacs stuff, respectively.
What I'm really looking for is an effective way to get Emacs to really understand the project, beyond just highlighting. Etags looks like a good option, but it looks like the process for generating new tags is kind of arduous and manual (or at least not invisible). The nice thing about Etags is that they integrate well with Anything and Auto-Complete. Other potential options are gtags (though I'm hesitant to install non-elisp files, just for the complexity), vtags, or Semantic, which I've messed with before and seems complicated to set up, plus it doesn't look like it has support for PHP.
Another option is Imenu, but it only works for the current buffer, and I would like to be able to jump to function definitions in other files (preferably using Anything for completion of the name).
The projects I will be working on are not that big (about 30,000 lines total), so the overhead of Etags probably won't be that big of an issue, but I'd rather not use it if there is a better solution.
So what is your preferred PHP editing system?
In addition to features you are already familiar with, I suggest you the followings.
ETags
I do not use ETags, but there is a question already on SO How to programmatically create/update a TAGS file with emacs. No good answer was posted, though, but it may be a good entry point to get an idea.
Debugging
Flymake is a mode to get on the fly syntax checking. It has support for PHP as well. It hints at syntax errors immediately as you type. The Flymake version shipped with Emacs 23 contains PHP support. If you have previous version, check Sacha Chua's post on Emacs and PHP: On-the-fly syntax checking with Flymake.
Another useful package is Geben that allows you to debug your scripts interactively. For PHP, you can use XDebug. There is a detailed tutorial on how to do that, see Debug php in emacs with geben.
Documentation lookup
PHP Mode has a nice feature to lookup the function's definition in PHP's manual in your web browser (M-x php-search-documentation or C-c C-f). You can combine it with Emacs-W3M to get the relevant manual page without leaving Emacs.
web-model.el (available on web-mode.org) handles pretty well php blocks embedded in an html document. This major mode will also highlight js and css parts.
As an alternative to ETags, consider GNU Global, aka "GTags". Global is a lot smarter about finding tags tables, and is fairly fast to update. Emacs-fu has a nice post about doing this on-the-fly.
BTW, if you're using the Windows port of GNU Global with a Windows Emacs build, use the DJGPP ("DOS") version. The MinGW ("Win32") build seems to have a problem with path names.
In addition to the answer given on May 28 '09, I think I can add some packages to it which enhanced my PHP experience on Emacs.
Auto-completion
ac-php is in my opinion a good additions to Etags. All references to a tag will be found with etags, but the definition with ac-php. ac-php is also configurable to which directories should be included. For example, while developing a wordpress plugin, you can add a reference to the directory containing the wordpress files in .ac-php-conf.json (which resides in the project root) and it will auto-complete, jump to reference, etc. This package supports company-mode and auto-complete.
Here's an example configuration of ac-php:
(use-package ac-php
:ensure t
:bind (:map
php-mode-map
("M-+" . ac-php-find-symbol-at-point)
("M-]" . ac-php-location-stack-back)
("<menu> r" . ac-php-remake-tags)
("<menu> R" . ac-php-remake-tags-all)))
Another option would be to use phpactor, but the Emacs interface is at the time of writing still in alpha stage, with which I also hardly have any experience - except for the constructor completion, which works pretty well.
Error checking
In addition to syntax errors, Flycheck supports phpMessDetector and phpCodeSniffer out of the box. This enables you to have more enhanced notice/warning/error reporting based on supported coding standard and best practices.
Another package I like for static analysis is PHPStan Emacs interface, which reports potential errors in your code (including incorrect type hints).
Additional formatting
I also use phpcbf (which apparantly is archived). This package formats the buffer into the wanted coding standard.
Semantic
For anyone in the dark, Semantic is a built-in Emacs package and provides IDE like features. Here's an example how to include semantic for php-mode:
(add-hook 'php-mode-hook (lambda ()
(require 'semantic/symref/grep)
(add-to-list 'semantic-symref-filepattern-alist '(php-mode "*.php" "*.inc"))
(semantic-mode)))
Imenu
For including imenu jumping to definitions, another example configuration:
This is the sidebar for jumping to in-file methods and functions.
(use-package imenu-list
:ensure t
:config
(setq imenu-list-focus-after-activation t)
:bind (:map php-map
("<menu> \\" . imenu-list-smart-toggle)))
Example config for helm support in jumping to definitions in all project files:
(use-package imenu-anywhere
:ensure t
:after helm
:bind (:map php-map
("<menu> |" . helm-imenu-anywhere)))
Additional debugging
Besides geben, I like to use psysh, which by dropping in eval(\Psy\sh()); gives a repl on that line of code and gives access to all definitions and whatever else one would have access to (ofcourse, after requiring it in composer).
More generally handy packages
Snippets
Maybe a bit obvious for everyone already experienced with Emacs, but yasnippet is also very handy for writing your own templates. There are also packages that include a lot of predefined templates for all sorts of languages, but I write my own to keep Emacs a little less bloated than my set-up already is, it also helps me remember them more easily.
Project management
Excuse the obviousness again, but Projectile is also a very good package which by default includes git support for scoping the project.
Offline documentation
If you use Zeal for offline documentation browsing, there's also zeal-at-point. Example configuration, if you use, lets say: PHP, CodeIgniter and WordPress:
(use-package zeal-at-point
:ensure t
:bind (("<menu> z" . zeal-at-point))
:config
(add-to-list 'zeal-at-point-mode-alist '(php-mode . ("codeigniter" "wordpress" "php"))))
I'm currently using Vim as a lightweight IDE. I have NERDTree, bufexplorer, supertab, and ctags plugins which do almost everything I want. Only big thing missing for me is auto code formatting.
I'm working with some messy PHP code which has inconsistent indenting and code formatting, ideally I could highlight the code I want formatted (whole files would be fine too) and run a command to tidy it.
Does anybody have a nice solution for this working in Vim?
Quick way to fix PHP indentation in vim is to visually select the lines you want to work with using shift-v, and then press equals (=) to trigger auto-formatting.
As for other formatting issues you're probably looking at employing some regex search and replaces, such as :%s/^M/\r/g (that's ctrl-V ctrl-m, not caret-M) to fix line endings
Enter normal mode in vim and then type
1GVG=
Format in PSR-2 style
For the new standard Coding Style Guide PSR-2 use the PHP-CS-Fixer.
There is a Vim plugin: Vim-php-cs-fixer
How to install:
Install PHP-CS-Fixer (globally with Composer):
composer global require friendsofphp/php-cs-fixer
Then add the Vim plugin (Pathogen):
cd ~/.vim/bundle
git clone git#github.com:stephpy/vim-php-cs-fixer.git
Restart Vim.
Default mapping:
<leader>pcd " For directory
<leader>pcf " For flie
There is a vim plugin that enables formatting on your code from within vim. It's called vim-autoformat and you can read about it and download it here:
https://github.com/vim-autoformat/vim-autoformat
It integrates external code-formatting programs into vim. When this plugin is installed, you only have to install an external code formatter to get everything to work out of the box. It supports the php formatter phpCB, which is the best php formatter i've seen so far.
UPDATE: phpCB is not supported anymore, due to code breaking behaviour. However, vim's indentfile is always used as fallback, allowing you to at least indent your code when there's is no formatter available.
The vim website is not the easiest to navigate, but there is a wealth of chewy nougat center there.
For instance I found this php indenting script there. Give it a try.
I'm using a pre-commit hook to lint-check PHP source submitted by our staff, and everyone's really happy with the results. The staff have agreed it would be useful to have the code re-formatted to follow (customizable) style rules on commit. Are there any FOSS scripts which can do this from the command-line?
PHP_CodeSniffer is a nice PEAR package, but it only sniffs the PHP documents for detecting violations of coding standards - it doesn't fix the violations or re-formats the documents. However, it's a great package that every PHP-developer should at least know about - and maybe you can get your fellow staff members to sanitize their code on their own.
You can edit the sniffing-filter in PHP_CS the way you want it to work. I on the other hand likes the default settings, which is at least a good start for writing better code.
Was looking for the same thing, just came across the PHP Beautfier package in the PEAR repository:
http://pear.php.net/package/PHP_Beautifier
Hope this helps!
Not quite an answer, but since you bring it up, there should be a command line PHP beautifier. Until then you're stuck with sed to fix tabs.
The problem is, its very difficult to write something like what you want without writing a parser for the PHP language. So, if someone were to write such a tool, it should also provide lint functionality, be platform independent and released under a very unrestrictive license.
Considering the above, I think that's why one doesn't (currently) exist (that I could find). I'm posting this as an answer to say thanks for the idea, which is also why this is CW.
Not on the command-line but perhaps useful: PHP/Eclipse can do auto source formatting and I think you can run it on an entire project in one go. http://www.phpeclipse.com/ .
How can I measure number of lines of code in my PHP web development projects?
Edit: I'm interested in windows tools only
Check CLOC, it's a source code line counter that supports many languages, I always recommend it.
It will differentiate between actual lines of code, blank lines or comments, it's very good.
In addition there are more code counters that you can check:
SLOCCount
sclc
USC's CODECOUNT
loc
Ohcount
phploc
No experience if it runs on Windows, tho, but searching on the web showed some results of people getting it to work on Windows..
If you are on a linux box, the easiest way is probably directed by this SO question:
count (non-blank) lines-of-code in bash
Our SD Source Code Search Engine is a GUI for searching across large bodies of source code such as a PHP web site. It is fast because it preindexes the source code.
As a side effect of the indexing process, it also computes metrics on the source code base, including SLOC, Comments, blank lines, Cyclomatic and Halsted complexity numbers.
And it runs on Windows.
If you are using VS code, install this extension called Lines of Code (LOC)
After installation, use ctrl+p, type linecount, and you will find below options.
Count Workspace files will give the output in the following format.
This works on any OS with VS Code with the above plugin installed.
npm install -g cloc
Go to the project folder
Delete the node_modules and dist folder (if you have any), Because you don't need to calculate loc in dist and node_modules
inside the project folder
run this command: cloc *
Output will look like this :
If you're using a full fledged IDE the quick and dirty way is to count the number of "\n" patterns using the search feature (assuming it supports regexes)