PSR2 with class declarations extending classes with namespaces in PHP Code Sniffer - php

I've hit a problem with PHPCS using the PSR2 standard. Have searched high and low but to my surprise I can't find anyone reporting the same issue.
Say I have a class declaration as follows:
<?php
class MyChildClass extends \SomeNameSpace\MyParentClass
{
}
Then I run it through PHPCS with:
bash-3.2$ phpcs -s --standard=PSR2 test.php
FILE: test.php
--------------------------------------------------------------------------------
FOUND 2 ERROR(S) AFFECTING 1 LINE(S)
--------------------------------------------------------------------------------
3 | ERROR | Expected 0 spaces between "SomeNameSpace" and comma; $1 found
| | (PSR2.Classes.ClassDeclaration.SpaceBeforeComma)
3 | ERROR | Expected 1 space before "MyParentClass"; 13 found
| | (PSR2.Classes.ClassDeclaration.SpaceBeforeName)
--------------------------------------------------------------------------------
Time: 0 seconds, Memory: 4.00Mb
Also:
Bash-3.2$ phpcs --version
PHP_CodeSniffer version 1.3.6 (stable) by Squiz Pty Ltd. (http://www.squiz.net)
Has anyone come across this? Am I doing something wrong? Otherwise I'm going head first into the sniffer code - which doesn't feel right.

The PSR-1 and PSR-2 standard inside the current release of PHP_CodeSniffer are not complete. I didn't ever mention them in the release notes so people obviously either just found them, or they are talking about the current dev version, where they are complete.
If you want to try out the complete version of PSR-2 inside PHP_CodeSniffer, you'll need to clone the git repo and use it directly:
git clone git://github.com/squizlabs/PHP_CodeSniffer.git
cd PHP_CodeSniffer
php scripts/phpcs --standard=PSR2 /path/to/code
Or you can wait for the official release, which I'm planning for sometime next week, assuming no major issues are reported.
If you run the latest dev version on the code you supplied, you'll get this:
2:PHP_CodeSniffer gsherwood$ php scripts/phpcs --standard=psr2 temp.php
FILE: /Users/gsherwood/Sites/Projects/PHP_CodeSniffer/temp.php
--------------------------------------------------------------------------------
FOUND 2 ERROR(S) AFFECTING 2 LINE(S)
--------------------------------------------------------------------------------
3 | ERROR | Each class must be in a namespace of at least one level (a
| | top-level vendor name)
5 | ERROR | Expected 1 blank line at end of file; 0 found
--------------------------------------------------------------------------------
Time: 0 seconds, Memory: 4.25Mb
Hope that helps.

Related

VScode PHPCS Extension Error: Referenced Sniff "WordPress-Core" does not exist

I want to add PHP CodeSniffer to VScode.
Within VScode I am getting the error 'phpcs: Referenced sniff "WordPress-Core" does not exist'
However when I run the following command in the terminal:
phpcs --standard="WordPress-Core" dropdowns.php
PHP CodeSniffer works as expected with the following terminal output:
--------------------------------------------------------------------------------
FOUND 34 ERRORS AND 17 WARNINGS AFFECTING 51 LINES
--------------------------------------------------------------------------------
15 | WARNING | [x] Array double arrow not aligned correctly; expected 10
| | space(s) between "'id'" and double arrow, but found 1.
17 | WARNING | [x] Array double arrow not aligned correctly; expected 4
| | space(s) between "'taxonomy'" and double arrow, but found
| | 1.
18 | WARNING | [x] Array double arrow not aligned correctly; expected 5
| | space(s) between "'orderby'" and double arrow, but found
| | 1.
34 | WARNING | [x] Equals sign not aligned with surrounding assignments;
| | expected 10 spaces but found 1 space
35 | WARNING | [x] Equals sign not aligned with surrounding assignments;
| | expected 7 spaces but found 1 space
36 | ERROR | [x] Short array syntax is not allowed
44 | WARNING | [x] Equals sign not aligned with surrounding assignments;
| | expected 2 spaces but found 1 space
84 | WARNING | [x] Equals sign not aligned with surrounding assignments;
| | expected 2 spaces but found 1 space
My settings.json file looks like this:
{
"workbench.colorTheme": "Default Light+",
"window.zoomLevel": 0,
"phpcs.standard": "WordPress",
"phpcs.executablePath": "/Users/michelle/.composer/vendor/bin/phpcs",
"phpcs.enable": true,
"phpcs.showWarnings": true,
"phpcs.showSources": true,
}
My phpcs.ruleset.xml looks like this:
<?xml version="1.0"?>
<ruleset name="WordPress Theme Coding Standards">
<description>My Project's Coding Standards</description>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPressVIPMinimum"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-VIP-Go"/>
</ruleset>
I solved this error by updating the rule references in this file:
~/.composer/vendor/wp-coding-standards/wpcs/WordPressto also be absolute paths. Final ruleset.xml for WordPress coding standards now looks like this:
<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="WordPress" namespace="WordPressCS\WordPress" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">
<description>WordPress Coding Standards</description>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
<rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra">
<!-- Prevent duplicate messages + deprecation notice from deprecated sniff. -->
<exclude name="WordPress.WP.TimezoneChange.timezone_change_date_default_timezone_set"/>
<exclude name="WordPress.WP.TimezoneChange.DeprecatedSniff"/>
</rule>
</ruleset>
There is a good chance that you're using multiple versions of phpcs.
Try, in a shell:
which phpcs
If you get something like /usr/bin/phpcs, you have the package installed with your system's package manager. Either manage it using the package manager -- install WordPress-Core with apt or brew or whatever you're using -- or remove it (then try again).
If you don't get a result, try to install PHPCS globally using Composer. Make sure ~/.config/composer/vendor/bin is in your PATH.
At this point, you know the path of the executable that you want to use, and you know where it is. Now:
phpcs -i
That will give you a list of installed standards. Mine says: MySource, PEAR, PSR1, PSR12, PSR2, Squiz, Zend, PHPCompatibility, PHPCompatibilityParagonieRandomCompat, PHPCompatibilityParagonieSodiumCompat, PHPCompatibilityWP, WordPress-Core, WordPress-Docs, WordPress-Extra and WordPress.
You know where your executable is and you know how to modify it (either Composer with global, or apt, or brew, or whatever). Keep installing until you get the right thing.
If you're using a PHPCS extension in VS Code and you haven't specified a full path to the executable, it may be checking in your project path. Given how easy it is to set up Composer with lots of stuff, it may be finding another copy of the executable.
Set the extension to point to the correct executable. Now it should be able to find all the standards you need.
Also make sure that you're not running multiple VS Code extensions. If you're anything like me, when you move to a new install, you go and install 50 extensions of all the things you think you may need one day. Some meta-extensions come with PHPCS, commonly bundled with a formatter, or, "everything you need to code in VS Code in PHP." Make sure that either:
only one extension is linting, or,
all linters are pointing to the correct phpcs executable.
This should fix this issue permanently.
you need to make all installed coding standards available to phpcs:
phpcs --config-set installed_paths full-wpcs-path\WordPress,full-wpcs-path\WordPress-Core,full-wpcs-path\WordPress-Docs,full-wpcs-path\WordPress-Extra
see phpcs.standard in:
https://marketplace.visualstudio.com/items?itemName=ikappas.phpcs

How can I provide a script for PHP CLI via composer (as standalone, and as dependency)

I am attempting to write a PHP script that I would like to run from the command line. I want to use composer to manage its dependencies, as well as to make it available to be installed as a dependency to other projects. I also want to maintain the ability to use it on its own (with its dependencies).
Currently, main.php is my "entry point" (what I would execute from the command line). As I built and tested it, I did so in the "stand alone" mindset. A such, main.php requires autoload like so:
<?php
require_once __DIR__.'/../vendor/autoload.php';
Continuing in stand alone mindset, I set it up like so:
git clone package into place
cd package
composer install
This produces the following directory setup"
package
|-composer.json
|
|-src
| |-ClassOne.php
| |
| |-ClassTwo.php
| |
| |-main.php
|
|-vendor
|-autoload.php
|
|-composer
|
|-3rdpaty_1
|
|-3rdpaty_2
This works well--I can run php src/main.php which is able to find the classes it needs because it loads __DIR__.'../vendor/autoload.php'.
Where I run in to trouble is when I want to install the package as a dependency to another project (in order to have the script available to run there). I add my package to the composer.json and it gets installed. Attempting to run php vendor/compnay/package/src/main.php fails, however, because the necessary autoload.php is in a different place:
dependent_project
|-composer.json
|
|-some_code
|
|-vendor
|-autoload.php
|
|-composer
|
|-company
| |-package
| |-composer.json
| |
| |-src
| |-ClassOne.php
| |
| |-ClassTwo.php
| |
| |-main.php
|
|-other_vendor_1
|
|-other_vendor_2
I understand what is wrong, but I am not sure how to fix it. How does one provide such a thing using composer? I've searched around a lot but I don't see anyone asking or answering the same question. I notice the bin property of composer.json and started looking into that idea, but I'm still not finding a lot of info on how to properly set up my script to find what it needs in the different contexts.
I considered trying to use include in an if, and running a second include to the other path on fail, but that doesn't seem like the proper way to go about it.
A common practice is to look into both locations for an autoload file. See for instance this snippet used by Behat:
function includeIfExists($file)
{
if (file_exists($file)) {
return include $file;
}
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
fwrite(STDERR,
'You must set up the project dependencies, run the following commands:'.PHP_EOL.
'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
'php composer.phar install'.PHP_EOL
);
exit(1);
}

Zend Framework 2 PHPUnit Test Error

Hi I am currently running through the ZF2 User Guide trying to run a PHPUnit Test on the skeleton application as outlined here http://zf2.readthedocs.org/en/latest/user-guide/unit-testing.html.
But even though I have not edited the Module and have copied all the files from the tutorial every time I run the PHPUnit Test in Zend Studio I get this error
Error:
Fatal error: Class 'ApplicationTest\Bootstrap' not found in C:\Program Files (x86)\Zend\Apache2\htdocs\exerciseDB\module\Application\test\ApplicationTest\Controller\IndexControllerTest.php on line 24
But when I click on the Bootstrap::getServiceManager(); on line 24 Zend Studio takes me to the correct method.
File Stucture:
module
|_Application
|_config
|_language
|_src
|_test
|_ApplicationTest
| |_Controller
| |_IndexControllerTest.php
|_Bootstrap.php
|_phpunit.xml.dist
|_TestConfig.php.dist
Can anyine tell me where I am going wrong?
This was a really annoying bug that is somewhat of an irritation. Your phpunit config seems to be changed slightly from the one on the skeleton application. To give you direct answer that fixed my issue I did the following...
module
|_Application
|_config
|_language
|_src
|_tests
|_ZendApplicationModule
| |_Framework
| |TestCase.php
| |_IndexControllerTest.php
| |_SampleTest.php
|_Bootstrap.php
|_phpunit.xml.dist
|_TestConfig.php.dist
With the base setup as outlined above from the skeleton APP I had to add
require_once 'Framework/TestCase.php';
To SampleTest.php
For your actual fix you will need to require_once the file that is generating the issue. That should fix it.
Also make sure to update your autoload_classmap.php
I ran into the same issue where phpunit was not seeing my "module/Application/test/phpunit.xml.dist" file (I had it miss-spelled)
Try adding the file directly to the command line:
phpunit --bootstrap Bootstrap.php .
I had the issue as well.
I solved it by running phpunit from the root of my ZF2 project with the following arguments:
./vendor/bin/phpunit
--bootstrap ./module/Rest/test/Bootstrap.php
One can also specify the Test suite to use:
./vendor/bin/phpunit
--bootstrap ./module/Rest/test/Bootstrap.php
./module/Rest/test/RestTest/Controller/RestControllerTest.php
more details here

Using phpunit CLI output in a php script

The CLI output from a phpunit test contains useful information, such as:
PHPUnit 3.6.4 by Sebastian Bergmann.
F
Time: 7 seconds, Memory: 5.50Mb
There was 1 failure:
1) testHandler::testItem
Failed asserting that page text contains <itest New Family Name>.
Driver.php:632
testHandler.php:29
S163.php:18
testHandler.php:46
FAILURES!
Tests: 1, Assertions: 97, Failures: 1.
I'd like to send this information to my test tracking software by way of a POST through php curl.
However I can't find a way of catching the information in my test class (which extends PHPUnit_Framework_TestCase).
Any help / thoughts would be appreciated.
The easiest way if you have a custom build solution seems to be:
phpunit | curl -X http://url
or
phpunit 2>&1 > output.txt && cat output.txt | curl -X http://url
or something like that.
If you are using a proper Continuous Integration server look into the --log-junit and --coverage-clover or other output formats like --log-json.
I don't see any reason why you would want to get the output programmatically while the test are running. It just seems to be a lot more work than gain. There are ways to extend PHPUnit to integrate it with bugtrackers though. Have a look at the PHPUnit_Framework_TestListener.

Problem with PHP_CodeSniffer and SVN pre-commit hook

I've recently downloaded the latest version of CodeSniffer (1.3.RC0). I prefer this version and not the stable one (1.2.2) because I want the "severity" feature.
I've modified an existing Drupal standard package to be compatible with this version of CodeSniffer and stablish my own severity policy. When I run the phpcs from command-line, I've no problems at all. It sniffs the code correctly, filters severity and works fine.
The problem comes when I try to automate the sniffs with the subversion pre-commit hook. It seems that the phpcs-svn-pre-commit script coming with this release is not working at all.
I've followed the guide in http://pear.php.net/manual/en/package.php.php-codesniffer.svn-pre-commit.php step-by-step, but when I commit a file with coding standard errors (detected by command-line execution of phpcs and my Drupal standard package), subversion simply lets the file pass and commits the changes.
Has anybody been in the same problem?
Thanks in advance.
EDITED: execution examples.
$ phpcs --standard=Drupal --severity=4 ak_gourmet.module
PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/mcrypt.ini on line 1 in Unknown on line 0
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626/IcePHP.so' - /usr/lib/php5/20090626/IcePHP.so: cannot open shared object file: No such file or directory in Unknown on line 0
FILE: ...ce/trunk/httpdocs/sites/all/modules/custom/ak_gourmet/ak_gourmet.module
--------------------------------------------------------------------------------
FOUND 21 ERROR(S) AFFECTING 27 LINE(S)
--------------------------------------------------------------------------------
17 | ERROR | Concat operator must be surrounded by spaces. Found "...
| | '<p>'. "; expected "... . "
17 | ERROR | Concat operator must be surrounded by spaces. Found "...
| | .'</p>';..."; expected "... .;..."
40 | WARNING | A comma should follow the last multiline array item. Found:
| | MENU_NORMAL_ITEM
53 | WARNING | A comma should follow the last multiline array item. Found:
...
Line added in subversion pre-commit hook (it is being executed):
# execute code sniffer with drupal standards
/usr/bin/scripts/phpcs-svn-pre-commit --standard=Drupal --severity=4 "$REPOS" -t "$TXN" >&2 || exit 1
Committing the incorrect file:
$ svn commit -m "Testing svn hook-precommit" ak_gourmet.module
Enviando ak_gourmet.module
Transmitiendo contenido de archivos .
Commit de la revisiĆ³n 5814.

Categories