Coder Social home page Coder Social logo

cakephp-codesniffer's Introduction

CakePHP Code Sniffer

Build Status Total Downloads Latest Stable Version Software License

This code works with squizlabs/php_codesniffer and checks code against the coding standards used in CakePHP.

This sniffer package follows PSR-12 completely and ships with a lot of additional fixers on top.

List of included sniffs

Which version should I use?

See version map.

Installation

You should install this codesniffer with composer:

composer require --dev cakephp/cakephp-codesniffer
vendor/bin/phpcs --config-set installed_paths /path/to/your/app/vendor/cakephp/cakephp-codesniffer

The second command lets phpcs know where to find your new sniffs. Ensure that you do not overwrite any existing installed_paths value. Alternatively, install the dealerdirect/phpcodesniffer-composer-installer composer package which will handle configuring the phpcs installed_paths for you.

Usage

โš ๏ธ Warning when these sniffs are installed with composer, ensure that you have configured the CodeSniffer installed_paths setting.

Depending on how you installed the code sniffer changes how you run it. If you have installed phpcs, and this package with PEAR, you can do the following:

vendor/bin/phpcs --colors -p -s --standard=CakePHP /path/to/code/

You can also copy the phpcs.xml.dist file to your project's root folder as phpcs.xml. This file will import the CakePHP Coding Standard. From there you can edit it to include/exclude as needed. With this file in place, you can run:

vendor/bin/phpcs --colors -p -s /path/to/code/

If you are using Composer to manage your CakePHP project, you can also add the below to your composer.json file:

{
    "scripts": {
        "cs-check": "vendor/bin/phpcs --colors -p -s --extensions=php src/ tests/"
    }
}

Running Tests

You can run tests with composer. Because of how PHPCS test suites work, there is additional configuration state in phpcs that is required.

composer test

Once this has been done once, you can use phpunit --filter CakePHP to run the tests for the rules in this repository.

Contributing

If you'd like to contribute to the Code Sniffer, you can fork the project add features and send pull requests.

Releasing CakePHP Code Sniffer

  • Create a signed tag
  • Write the changelog in the tag commit

cakephp-codesniffer's People

Contributors

ad7six avatar admad avatar antograssiot avatar arhell avatar bcrowe avatar cake17 avatar carusogabriel avatar cdburgess avatar ceeram avatar cleptric avatar d33vil avatar dakota avatar derekperkins avatar dereuromark avatar devcorrelator avatar jrbasso avatar lorenzo avatar markstory avatar masterodin avatar mirko-pagliai avatar narendravaghela avatar othercorey avatar phantomwatson avatar raul338 avatar ravage84 avatar rchavik avatar renan avatar swiffer avatar tersmitten avatar tiutalk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cakephp-codesniffer's Issues

Failing tests

There are several failing tests: http://bin.cakephp.org/view/1599780770

It's in the files with HTML and PHP's alternative syntax.

There was a rule about that syntax once: 90dcfed

But as you can see it was removed, which makes sense for that use case. However, I think alternative syntax shouldn't be used within classes. So maybe add the rule again, but just for .php files and have it ignore .ctp files for example?

Type hint sniffer

I've intially written this for my own projects, but after struggeling with some incompatible type hinting in Cake 3.x, I thought perhaps something like this could be useful for CakePHP too.

I've just made some quick and dirty changes in order to make it match the (assumed) CakePHP 3.x standards (mainly doc-block type hints should be fully qualified, method type hints should be unqualified and imported), and split it into its own standard so that you can easily try it: https://github.com/ndm2/ndmcake-codesniffer

I guess I don't have to explain it, but... clone into NDMCake and run phpcs --standard=/path/to/NDMCake/ruleset.xml /path/to/files or phpcs --standard=NDMCake /path/to/files (when cloned into CS standards folder).

What does this sniffer do? Well, it looks in method signatures and the @var, @param, @see, @return, @throws, @method and @property docblock tags, and among others it checks that:

  • Docblock type hints are present
  • Method type hints are present in case possible (depends on the docblock type hint)
  • Non-primitive docblock type hints are fully qualified
  • Method type hints aren't fully qualified unless pointing into the global namespace
  • Non-primitive type hints can be resolved (in case they are pointing into one of the available base packages, for example Cake)

Note that in order to be able to check whether a type can be resolved, the sniffer first parses all files and extracts namespaces and class/interface names, which can take a while.

So before I try to make this work better and massage it into the CakePHP standard, I thought I'd ask whether this would be considered useful at all?

Fix installation issues with composer

Currently when these code sniffs are installed with composer, they are unusable. Because the sniffs are installed into vendor/cakephp/cakephp-codesniffer, phpcs generates classnames like cakephp-codesniffer_Sniffs_Commenting_FunctionCommentSniff which clearly can never exist, resulting in fatal errors. I can see a few options to resolve this issue:

  1. Get PHPCS patched to allow sniffs to be loaded based on the ruleset name attribute.
  2. Rename the composer package and classnames to something like CakePHPCs. This has the drawback of forcing the PEAR installed package to also change names.

The DOC Comment must be not spaced

This error message is hard to understand, does it only apply to indented doc blocks? if so we could change it to

The DOC Block must not be indented

If it applies to any /** comment, I'm not sure what error message to suggest - but needs one that's a bit easier to understand :)

Sniffer rules add PHP 5.6 requirement

So this is kind of a weird one. I extended the FlashHelper to work with Bootstrap. When I did I went ahead and added some templates to help with generation. This is what I ended up with...

protected $_defaultConfig = [
    'linkClass' => 'alert-link',
    'templates' => [
        'dismiss' => '<button type="button" class="close" data-dismiss="alert" aria-label="{{label}}"{{attrs}}>{{content}}</button>',
        'dismissIcon' => '<span aria-hidden="true">&times;</span>'
    ]
];

This causes a phpcs error as the dismiss key has 134 characters on a single line. So I converted it to this...

protected $_defaultConfig = [
    'linkClass' => 'alert-link',
    'templates' => [
        'dismiss' => 
            '<button type="button" class="close" data-dismiss="alert" aria-label="{{label}}"{{attrs}}>' .
                '{{content}}' .
            '</button>',
        'dismissIcon' => '<span aria-hidden="true">&times;</span>'
    ]
];

This passes the sniffer rules so I pushed to the repo all well and good. I went to make some changes on my computer at home and I ended up with a fatal PHP error saying it expected a ] character. When I collapse everything back onto a single line the error goes away.

I'm not sure this is anything you guys would be responsible for in terms of updating your sniffer rules but it seems like such an obscure error that I just wanted to report it so you were aware.

I also seem to get conflicts when running an underscored method name such as...

protected function _getSomething()
{
}

With the underscore I get a PSR2 error. Without the underscore I get a CakePHP error. Weird. Here is the version I'm running at home. I'm not in the office so I don't have the exact output for that one but it's a fresh install of php 5.6.4.

dustin@Dustin:~/GitHub/internal$ php --version
PHP 5.5.20-1+deb.sury.org~precise+1 (cli) (built: Dec 21 2014 19:54:33) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
    with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans

Underscore conflict on protected methods

Hello,

It appears that we have sniffs wanting opposite things.

The following sniff wants you to have an underscore in front of protected method names:
CakePHP.NamingConventions.ValidFunctionName.ProtectedNoUnderscore

The following sniffs want you to -not- have an underscore in front of protected method names:
PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
Squiz.NamingConventions.ValidFunctionName.PublicUnderscore

Unit tests fail, a problem with input parameter `standard`

Standard's ruleset.xml location is hardcoded in PHP_CodeSniffer::getInstalledStandardPath() (l 2010):

relative to CodeSniffer.php:

./CodeSniffer/Standards/CakePHP/

where CakePHP will be the standard's name.

If that folder is not there, the standard is considered not installed. The entire test suite will then fail.

On the command-line, phpcs will be executed thus:

phpcs --standard=cakephp .

(standard's name is case-insensitive: PHP_CodeSniffer/CLI.php l 734)

blank line after namespace

PSR1:
There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declaration

There is no sniff currently for this

Cake2 - Advancement

Hi There

Is there a stylechecker for CakePHP 2.x or is it the same as for CakePHP 1.x?

Thank you for the information

Future PEAR support

I was just wondering how the PEAR support will be handled for the CakePHP CodeSniffer in the near future?
It seems the Composer support is already setup fine but the recommended installation is still PEAR.

Nested elseif indention is marked as invalid

The following test fails while it should pass.

inline_elseif_pass.php

<?php
$a = 'a';
if (!empty($a)):
    $b = 'b';
    if ($b === 'c'):
        $c = 'e';
    elseif ($b === 'd'):
        $c = 'f';
    else:
        $c = 'g';
    endif;
endif;
--------------------------------------------------------------------------------
FOUND 1 ERROR(S) AFFECTING 1 LINE(S)
--------------------------------------------------------------------------------
 8 | ERROR | Closing brace indented incorrectly; expected 0 spaces, found 1
--------------------------------------------------------------------------------

phpcs installed via composer - how to install cakephp?

When phpcs is installed via composer, I have the binaries in ~/.composer/vendor/bin. How can I install the CakePHP Codesniffer then? The pear package will install it into the autoload path in php, but wont it also install phpcs if this is not present?

Maximum character limitation

Do we really need this limitation check? I could not find any hint in cakephp docu. If we still need this then pls check if we have to stick to max 85 characters

Confusing error message missing @throws is attached to the last docblock found

This code:

<?php
class TheClass {

/**
 * Correct
 */
        public function correct() {
        }

        public function error() {
                throw new NotFoundException();
        }
}

Will produce this output

:) ~/html/skelapp $ phpcs --standard=CakePHP example.php 

FILE: /var/www/skelapp/example.php
--------------------------------------------------------------------------------
FOUND 1 ERROR(S) AFFECTING 1 LINE(S)
--------------------------------------------------------------------------------
 6 | ERROR | Missing @throws tag in function comment
--------------------------------------------------------------------------------

Time: 38 ms, Memory: 6.25Mb

Attaching the @throws error to the last docblock found in code and producing an incorrect message...

Thank you!

Unit Tests fail, a problem with input parameter 'standard'

PHP/CodeSniffer/CLI::process() expects array of strings

Standard parameter input is now:

  • An array of strings.
  • Each string must match a folder name in <php_dir>/PHP/CodeSniffer/Standards.

where <php_dir> is taken to be:

`pear config-get php_dir`

ruleset.xml is not in correct place

Standard's ruleset.xml location is hardcoded in PHP_CodeSniffer::getInstalledStandardPath() (l 2010).

Specifically, for a standard named cakephp, it is in <php_dir>/PHP/CodeSniffer/Standards/CakePHP/

If that folder is not there, the standard is considered not installed. The entire test suite will then fail.

On the command-line, phpcs will be executed thus:

phpcs --standard=cakephp .

(standard's name is case-insensitive: PHP_CodeSniffer/CLI.php l 734)

Camel caps format and blank lines

Example:

<?php
class Test {

    private static $__myVar = 1;

    public static function getMyVar() {
        return self::$__myVar;
    }
}

Output:

FILE: test.php
------------------------------------------------------------------
FOUND 2 ERROR(S) AFFECTING 2 LINE(S)
------------------------------------------------------------------
 7 | ERROR | Variable "__myVar" is not in valid camel caps format
 8 | ERROR | Expected 1 blank lines after function; 2 found
------------------------------------------------------------------
  • Error1: The name $__myVar is valid, but not when used with self::$__myVar or Test::$__myVar.
  • Error2: The message "Expected 1 blank" is OK, but "2 found"? Shouldn't be "0 found"?

Add a formal License/Copyright

While the project is a public GitHub repo and presumebly has the same copyright as the Cake core, it would be great if there was a formal copyright/license applied so that the community has confidence in our usage of this CodeSniffer.

More information, if needed, on why even projects in the open should have some license applied.

The requested package cakephp/cakephp-codesniffer could not be found in any version

Command: The requested package cakephp/cakephp-codesniffer could not be found in any version.

Error:

Changed current directory to /root/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package cakephp/cakephp-codesniffer could not be found in any version, there may be a typo in the package name.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

Wrapping long strings

On occasion there might be a long string, or a series of concatenations that pass well beyond the 80 character mark.

I'm not sure what the CakePHP standards are on long strings, but for readability, I like to limit the width at approx 80 characters wide.

Currently, the concatenation rule will complain about spaces after or before a concatenation, depending on where it has been placed.

i.e. Expected 1 space after ., but 2 found or Expected 1 space before ., but 8 found.

How should concatenation of long strings be handled under CakePHP coding standards?

1.x FunctionCommentThrowTagSniff

While doing some CS fixes in our code, I came accross FunctionCommentThrowTagSniff.php.

https://github.com/cakephp/cakephp-codesniffer/blob/master/CakePHP/Sniffs/Commenting/FunctionCommentThrowTagSniff.php

There is also an identically named sniff in the Squiz Standard:
https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php

It seems @jrbasso contributed it to support namespaces
86edcb8

Implemented sniff to validate @throws in PHPDoc with support to nameespaces

But it seems there is a probably related commit to the original Sniff around that time, too:
squizlabs/PHP_CodeSniffer@add2da9

Commit history for CakePHP's FunctionCommentThrowTagSniff.php
https://github.com/cakephp/cakephp-codesniffer/commits/ea8568edb5f2f7eaf0f536372f677de365b5d7c3/Sniffs/Commenting/FunctionCommentThrowTagSniff.php
https://github.com/cakephp/cakephp-codesniffer/commits/master/CakePHP/Sniffs/Commenting/FunctionCommentThrowTagSniff.php

Commit history for the original FunctionCommentThrowTagSniff.php
https://github.com/squizlabs/PHP_CodeSniffer/commits/master/CodeSniffer/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php

I haven't tried it yet, but couldn't we replace @jrbasso 's sniff with the original one?
May be @jrbasso can shed some light on this.

I'm asking because I also found a bug that exist in both sniffs. ;-)

Auto-fixing code not correclty checking if it should run

The auto fixes in the standard don't check if they are supposed to run, so they will run even if the list of sniffs is being filtered with the --sniffs command line argument.

Examples of the code that needs correcting are:
https://github.com/cakephp/cakephp-codesniffer/blob/phpcs-fixer/Sniffs/ControlStructures/ElseIfDeclarationSniff.php#L53
https://github.com/cakephp/cakephp-codesniffer/blob/phpcs-fixer/Sniffs/PHP/DisallowShortOpenTagSniff.php#L58

The change is fairly easy. Instead of:

$phpcsFile->addFixableError($error, $stackPtr, 'MessageCode');
if ($phpcsFile->fixer->enabled === true) {
    // Fixer code here.
}

You would write:

$fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAllowed');
if ($fix === true) {
    // Fixer code here.
}

The addFixableError() and addFixableWarning() methods will only return TRUE is the fixer is enabled and if the message is not being filtered out in some way.

PEAR issue?

Is there something wrong with the PEAR package?

I get:

the "CakePHP" coding standard is not installed

after installing with pear (on CircleCI):

pear channel-discover pear.cakephp.org
pear install --alldeps cakephp/CakePHP_CodeSniffer

It started failing after June 6th.

Alpabetical order of use

currently this is the only accepted order as correct alphabetical:
use Cake\Routing\RouteCollection;
use Cake\Routing\Route\Route;
use Cake\Routing\Router;

which imo should be:
use Cake\Routing\Route\Route;
use Cake\Routing\RouteCollection;
use Cake\Routing\Router;

or:
use Cake\Routing\RouteCollection;
use Cake\Routing\Router;
use Cake\Routing\Route\Route;

depending on how you treat the backslash

folder name should be CakePHP instead of Cake to avoid issues

Locally, with windows I always get this fatal error:

"2013-03-12 15:49:46 Error: Cannot redeclare class CakePHP_Sniffs_Commenting_FunctionCommentThrowTagSniff in [E:...\Vendor\PHP\CodeSniffer\Standards\Cake\Sniffs\Commenting\FunctionCommentThrowTagSniff.php, line 271]"
Seems like the autoloader does include a little bit too much here.

After I searched for a solution and found thomas-ernest/CodeIgniter-for-PHP_CodeSniffer#12 I changed the folder name to "CakePHP" and it worked!

So the folder name(s) should be the same as the class name (which makes sense).

I then used

--standard=CakePHP

then and phpcs ran just fine.

Codesniffer for CakePHP 3

Hi there - I've been coding using CakePHP 3, and I was wondering when the release of CodeSniffer for that might be out (or if it's out, where it's at).

I have the current one set up, but I'm getting errors that must be referencing older versions of CakePHP. (Line max is 85 rather than the suggested 100-120 on the current documentation, opening function bracket suggested on a new line rather than one space after on the current line, etc. etc.)

Ignore PHP Variables

After using file_get_contents, I access $http_response_header to get the response data. I have Codesniffer enabled as a pre-deploy check. Can I get it to ignore this case when it's a variable name that I can't change?

About tabs and spaces in coding standards

This is not a bug report, but a question (sorry if this is not the place to ask it).
I've been reading php-fig standards and coding styles. In coding styles they say:
"Code MUST use 4 spaces for indenting, not tabs."

But CakePHP still use tabs as coding standard. Does CakePHP, as a member of the project, plan to change that?

Greetings!

Origin of "Doc blocks must not be indented" ?

"Doc blocks must not be indented" forces doc blocks to not be aligned to method declarations.

The PSR, PEAR & Zend styles don't enforce the "no indent" so I'm curious where this comes from?

We should switch to phpcs-fixer branch in 3.x some time.

Working with the phpcs-fixer branch quite some time now, I think we should switch to it completely some time in the 3.x development.

It would fairly decrease the time to fix trivial CS errors, as all you need to do is to apply -f etc and all those issues will automatically be fixed for you - a real time safer.

A CakePHP3.0 compatible wrapper plugin for it can be seen and tested here: https://github.com/dereuromark/cakephp-codesniffer/tree/3.0#phpcs-auto-fixer

There is already a branch for it in the official CakePHP repo - just a little bit outdated at the moment:
https://github.com/cakephp/cakephp-codesniffer/tree/phpcs-fixer
It contains phpcs-fixer compatible versions of the CakePHP sniffs.

A few more current ones and extra goodies can be found in https://github.com/dereuromark/codesniffer-standards repo.

v0.1.24 broke Pear.

israel@retina ~/_mojo/git-repos/marketplace (master) $ sudo pear install --alldeps cakephp/Cakephp_CodeSniffer-0.1.23
downloading CakePHP_CodeSniffer-0.1.23.tgz ...
Starting to download CakePHP_CodeSniffer-0.1.23.tgz (25,093 bytes)
.........done: 25,093 bytes
install ok: channel://pear.cakephp.org/CakePHP_CodeSniffer-0.1.23
israel@retina ~/_mojo/git-repos/marketplace (master) $  phpcs -p -v -n --extensions=php --standard=CakePHP --
^C
israel@retina ~/_mojo/git-repos/marketplace (master) $ sudo pear uninstall cakephp/Cakephp_CodeSniffer
uninstall ok: channel://pear.cakephp.org/CakePHP_CodeSniffer-0.1.23
israel@retina ~/_mojo/git-repos/marketplace (master) $ sudo pear install --alldeps cakephp/Cakephp_CodeSniffer-0.1.24
downloading CakePHP_CodeSniffer-0.1.24.tgz ...
Starting to download CakePHP_CodeSniffer-0.1.24.tgz (29,198 bytes)
.........done: 29,198 bytes
install ok: channel://pear.cakephp.org/CakePHP_CodeSniffer-0.1.24
israel@retina ~/_mojo/git-repos/marketplace (master) $  phpcs -p -v -n --extensions=php --standard=CakePHP --
ERROR: the "CakePHP" coding standard is not installed. The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz and Zend
israel@retina ~/_mojo/git-repos/marketplace (master) $ 

Repeats on Travis-CI, etc. ruleset.xml seems to be missing.

Wrong exclude pattern to ignore git internals

Any reason we want .git in any absolute path to qualify for ignore?

The following means even /User/memyself/Documents/cakephp.git/* is ignored.

<exclude-pattern>\.git</exclude-pattern>

Proposed changed:

<exclude-pattern>*/\.git/*</exclude-pattern>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.