GithubHelp home page GithubHelp logo

joomla / coding-standards Goto Github PK

View Code? Open in Web Editor NEW
128.0 57.0 129.0 1.54 MB

Joomla Coding Standards Definition

Home Page: https://developer.joomla.org/coding-standards/basic-guidelines.html

License: GNU General Public License v2.0

PHP 100.00%
joomla php phpcs php-codesniffer

coding-standards's People

Contributors

babsgosgens avatar brianteeman avatar chdemko avatar cristinasolana avatar dongilbert avatar eddieajau avatar elinw avatar elkuku avatar florianv avatar genr8r avatar hackwar avatar hleithner avatar hutchy68 avatar ianmacl avatar javigomez avatar louislandry avatar mbabker avatar nternetinspired avatar pasamio avatar philetaylor avatar photodude avatar rdeutz avatar realityking avatar roland-d avatar rvsjoen avatar stefanneculai avatar vess avatar wilsonge avatar yvesh avatar zero-24 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

coding-standards's Issues

problem with git clone http://github.com/joomla/coding-standards.git `pear config-get php_dir`/PHP/CodeSniffer/Standards/Joomla

If I use the command

git clone http://github.com/joomla/coding-standards.git pear config-get php_dir/PHP/CodeSniffer/Standards/Joomla

I get

Cloning into /usr/lib/php/pear/PHP/CodeSniffer/Standards/Joomla...
remote: Counting objects: 101, done.
remote: Compressing objects: 100% (72/72), done.
remote: Total 101 (delta 44), reused 85 (delta 28)
Receiving objects: 100% (101/101), 55.56 KiB, done.
Resolving deltas: 100% (44/44), done.
error: refs/remotes/origin/master does not point to a valid object!
error: Trying to write ref refs/heads/master with nonexistant object 893dc8b
fatal: Cannot update the ref 'HEAD'.

I can clone the repository with tower so not a big issue but maybe someone can take a look.

Cheers,
Robert

[PHPCS 2.x] PHP 7 constructs

I don't have anything set up to run PHPCS against a PHP 7 project, but for something like https://github.com/joomla/help.joomla.org which is using PHP 7 features like scalar typehints and return type declarations, or a project that might use grouped use statements (example below), is PHPCS going to blow up in our faces or are we good to go with it?

<?php
namespace Joomla\Project\Model;

use Joomla\Model\{
	StatefulModelInterface, StatefulModelTrait
};
use Psr\Log\{
	LoggerAwareInterface, LoggerAwareTrait
};

class MyModel implements StatefulModelInterface
{
	use StatefulModelTrait;
}

Changes in the tag requirements

I'm pasting this message here so we all are aware:

Michael Babker
Sep 23

to Production Leadership Team
I regenerated the docs for api.joomla.org as part of my release execution and the current version of phpDocumentor is throwing new errors on having multiple @package tags in a file. In the CMS, we currently place @package and @subpackage tags in both the file and class doc block, and those are duplicated lines of information that aren't necessary in both doc blocks. As the CMS classes are not namespaced, the use of @package and @subpackage is required to group our code into appropriate packages. Namespaced code (like the Framework) uses the namespace as the grouping.

Given that phpDocumentor is now throwing errors over our duplicated tags, and them not being a true requirement in multiple doc blocks, would it be an issue to make the @package and @subpackage tags not required in the CMS codestyle sniffs for class doc blocks (a change that is consistent with the sniffs in the main coding-standards repo) and allow folks to remove these tags from class doc blocks?

screen shot 2014-09-23 at 17 34 24

The @package and @subpackage tags would be not required in class doc blocks but would still be required in the file doc block, as it is today. Those tags typically aren't used in method doc blocks or inline style doc blocks.

No other changes are being proposed right now.

Removing redundant ternary conditionals

I figured this would have to do more with coding standards and it was pointed out the discussion should continue here.

Discussion so far can be read here:
joomla/joomla-cms#4936

Do we agree on removing the redundant operators?

I agree with the final post on that PR. Thoughts?

[RFC] consider styleci for code enforcement

see https://styleci.io/

styleci is a PHP Coding Style Service that integrates with github and enforces code style. StyleCI can be configured to automatically create a pull request with fixes and immediately merge the same pull request if you'd like.

It's like PHPCS only as a CI service. Seems like it could be a good companion. Free for Open source projects too.

decide about spaces after/before exclamation mark

In this PR https://github.com/joomla/joomla-cms/pull/7292/files#r33676349 the question raised if we should allow or deny a space after a exclamation mark in a condition. There is a longer discussion about this here: https://github.com/php-fig/fig-standards/issues/102 and https://github.com/php-fig/fig-standards/issues/165.

so how should we write it:

a)

    if ( ! condition) 

Space before and after the exclamation mark

or

b)

    if (!condition)

Happy commenting :-)

Support for alternative syntax

Is there currently a way to avoid errors when using a inline php syntax?
Like this:

<?php if ($condition == true) : ?>
    <p>Yes</p>
<?php endif; ?>

do-while throwing an error

Or a warning - can't recall, but the code standards complain about a structure like this:

do
}
    // something
}
while ($condition);

From memory it says there should be a new line before the while.

Javascript Standards

I think it's worth considering some revisions to the JS coding standards as there are a few things about them at the moment that stand out to me as a little funny. I know people sometimes get overly sensitive about this kind of stuff but, let's face it, much of any coding standard is just arbitrary. Considering that, a coding standard should be as easy for the developer to follow properly as possible.

In PHP, we have PHPCS which can find and explain any CS errors you may have. If you have a decent IDE, you may even be able to hook it up to show your CS errors in real time. This kind of thing makes it really easy to write properly formatted code the first time and avoid going back over your code just to clean up the style.

For Javascript, we don't have such a thing (that I know of) but we do have jsbeautifier which will clean up your code automatically. Whatever the standard is, it would be best if it can be defined as jsbeautifier settings without exceptions. That way:

  • Cleaning up any file (old or new) is just a single command instead of a bunch of manual checks
  • The developer doesn't have to care too much about all details of the standard while coding
  • A test can easily be set up to determine if the code in a PR adheres to the standard

This mostly works today except for a few parts of the Joomla JS standard which should probably change:

  • The exceptions for spacing around function arguments
  • Maybe the rule about chained function calls

That's all. Change that and correct js formatting can just be automatic.

There's at least one more change that would really help which is unrelated to jsbeautifier. In PHP, our multiline comments are like:

/**
 * Start with two asterisks.
 * One asterisk on each subsequent line.
 */ 

But in JS, it's like:

/*
** Start with one asterisk.
** Two on each subsequent line.
*/

A good ide can help a lot with writing comments and especially docblocks but it may be difficult or troublesome to configure different styles for different languages. Why should we have such a different standard for something that doesn't matter at all? Let's just keep this part the same between Javascript and PHP.

PSR

Is there a plan to use PSR-2+ as Joomla coding standard? Is any PSR standard accepted for use within Joomla? It came accross my mind when I realized opening braces for control structures must go on a newline for Joomla, and knowing that Andrew Eddie was participating in php-fig for Joomla, I was wondering what is the plan with this, if any?

Ternery operators

@mbabker raised a question in this PR About Ternery operators and allowing or disallowing multi-line use.

I think multi-line ternary operators could have a benefit, if they improve the readability of the code. I would definitely suggest disallowing nested or stacked ternary operators as those situations just create a mess for code readability and maintenance.

With that said; based on some things I have recently read, I question even allowing ternary operators. Or at least we should be strongly discouraging them.

In general I think if a code standard or code style guidelines achieve the following then they are probably something that should be considered for adoption.

  • Does it improve code consistency?
  • Does it improve code readability?
  • Does it improve future maintainability?
  • Does it improve code portability?
  • Does it improve code performance?
  • Does it improve code security?

So applying those questions to ternary operators:

  • They are a deviation from standard if/else, thus creating a question of consistency.
  • They generally reduce readability
  • They generally reduce maintainability
  • They can reduce performance (since ternary operators do a copy operation, as such larger data sets will cause more performance issues)
  • As for portability, and security I don't know of any pros or cons.

I would also say that there are places where short hand code is discouraged or not allowed in the existing standard (PHP tags for instance). So this maybe another area where the short hand operators may not be the best choice, and should be disallowed or strongly discouraged.

CamelCase enforcement in namespaced classes

From what I remember, part of our camel case rule with class names came from how JLoader in the CMS is designed and how it splits classes based on camel casing to align to the filesystem; it couldn't cope with multiple uppercase letters. As our namespaced code is following PSR-4 standards, this is less of an issue. So, throwing the idea around, IMO we have a couple of options for how to manage that.

  • Continue enforcement of the camel case rule
  • Allow non-camel cased class and namespaces

Technically neither one is an issue, it's probably more of a consistency thing than anything. But, with allowing the non- option, you can represent a proper name correctly and not impose styling rules on them (i.e. Joomla\Cache\XCache versus Joomla\Cache\Xcache or Joomla\GitHub\GitHub versus Joomla\Github\Github).

Thoughts?

//cc @nonumber

Bug with Joomla.WhiteSpace.ControlStructureSpacing sniff

The below code block causes errors with the code sniff rules due to the comment between preceding the else keyword.

// If the data is a scalar value simply add it to the stream context options.
if (is_scalar($data))
{
    $options['content'] = $data;
}
// Otherwise we need to encode the value first.
else
{
    $options['content'] = http_build_query($data);
}

Support {@inheritdoc}

Let's consider allowing the {@inheritdoc} tag.

This really helps when extending classes, you don't have to rewrite whole docblock and keep it up to date with docblock changes in base class.

Important bonus is that one can easily see that the property has a parent.

At this moment php code sniffer complains like:

50 | ERROR | Doc comment for "$form" missing
52 | ERROR | Missing @return tag in function comment

This tag is being widely used in projects like Symfony and Drupal.

Usage

class A
{
    /**
     * Foo method
     *
     * @param   array  $bar  Bar
     *
     * @return  void
     */
    public function foo(array $bar)
    {
    }
}

class B extends A
{
    /**
     * {@inheritDoc}
     */
    public function foo(array $bar)
    {
    }
}

References

Formatting inline array and closures

There are a few formats that seem to be gaining popularity. See the following examples:

// Inline array.
$foo = bar($arg1, array(
    'one',
    'two',
    'three',
), $arg3);

// Inline closure.
$container->share('database', function(Container $c) {
    // Return a database driver.
}, true);

How do people feel about those cases?

Change code style for doc blocks

I would like to propose a style change for doc blocks.

The most painful action when formatting doc blocks is the spacing for @params.

Currently required are 3 spaces before the var type and 2 spaces separating type, name and comment.
I would like to use 1 space separating them.

Example:

before:
* @param   string  $string  The string.
after:
* @param string $string The string.

All modern IDE should parse this just fine.

If this is accepted, I will propose the corresponding code.

Thanks for your attention ;)

Move all Platform @since version numbers into Joomla version numbers

We have several @SInCE tags in the code, something like:

/**
 * HTTP response data object class.
 *
 * @since       XX.X
 */

Some of that @SInCE tags are showing Platform numbers. Instead we should change them for the corresponding Joomla version at that time. So for example https://github.com/joomla/joomla-cms/blob/ea05ad099fca9325d5d9e15d0f2bf34be0cb90c8/libraries/joomla/http/response.php#L17 says 11.4 meaning the Joomla Platform 11.4 that was released on February 2013 http://developer.joomla.org/news/20-version-11-4-of-the-joomla-platform-released.html

We should change it for the next stable version of Joomla that was released after February 2013. If we check the Joomla version history: http://docs.joomla.org/Joomla_2.5_version_history we found that after February 2013 was released Joomla! 2.5.10 (24 April 2013)

So this line https://github.com/joomla/joomla-cms/blob/ea05ad099fca9325d5d9e15d0f2bf34be0cb90c8/libraries/joomla/http/response.php#L17 should be switched to 2.5.10

We need to switch all tags @SInCE from platform version numbers into joomla version numbers

Updates to IDE xml's - Version note them?

Do we need to version out the IDE xml's? Or are we assuming every dev will have the latest version of their IDE of choice?

@betweenbrain you have https://github.com/betweenbrain/phpstorm-joomla-code-style/blob/master/Joomla.xml which works with the latest phpstorm? Or a specific version? For what version did @elkuku push.

There is also a PR version for fixes to Eclipse Kepler, assuming the current one for Eclipse is for Indigo. Current xml file is 2 years old.

Update Manual to BS3

If someone's bored one day and wants something to do, IMO, we can and should update the manual to Bootstrap 3 at some point instead of living on 2.3.2 forever and ever.

Is 150 characters maybe to few

Originally the reason for having 150 chars was to be able to print the code so it fits in one page. But I don't think no one prints code today.

Of course is not nice to have looooooong lines, but there are cases like when you add default values to the params of a function where I think we should be more flexible giving more than 150 chars:

screen shot 2014-10-09 at 13 21 25

What do you think?

editor standards

I recall there being a set of standards for the IDE editor such as tab vs spaces
image
but I can't seem to find any documentation on it anymore... Might be a good thing to add here.

Formating for pcre regx patterns

After some performance testing and consideration for readability, I think that patterns like [0-9] or [[:digit:]] is better than \d as the meaning is more clear. Since there seems to be no performance difference between any of these patterns; readability is prefered over the more condensed version.

Expression Meaning Prefered option 1 Prefered option 2
\d any decimal digit [0-9] [[:digit:]]
\D any character that is not a decimal digit [^0-9] --
\w any alphanumeric character (aka word character) [a-zA-Z0-9_] [[:word:]]
[a-z] Lowercase letters [a-z] [[:lower:]]
[A-Z] Uppercase letters [A-Z] [[:upper:]]
\xYY Hexadecimal character YY [0-9a-fA-F] [[:xdigit:]]

Preference to readability for pcre/regx patterns should be included in the coding standard.

Obsolete branches

The branches 'additions' and 'tmpl' can/should be removed - they were merged in 2013.

Lambdas are a thing now

I think the standard needs to be relaxed a little bit for lambdas (if possible).
For example:

$mapped = array_map(function ($a) { return $a->prop; }, $someObjects);

Will produce two phpcs errors:

  • Closing brace must be on a line by itself
  • Each PHP statement must be on a line by itself

So then, you might try:

$mapped = array_map(function ($a) {
        return $a->prop;
    }, 
    $someObjects
);

Which is already terrible but then you get:

  • Opening parenthesis of a multi-line function call must be the last content on the line
  • Closing brace indented incorrectly; expected 2 spaces, found 3

So you try:

$mapped = array_map(
    function ($a) {
        return $a->prop;
    }, 
    $someObjects
);

And somehow it works but it's hideous.

Formatting XML files

Currently CMS mixes few formats:

<fieldset
    name="group"
    label="FIELDSET"
    >

    <field
        name="show"
        type="radio">
            <option value="0">JHIDE</option>
            <option value="1">JSHOW</option>
    </field>
</fieldset>

and

<fieldset
    name="group"
    label="FIELDSET"
>
    <field
        name="show"
        type="radio"
    >
        <option value="0">JHIDE</option>
        <option value="1">JSHOW</option>
    </field>
</fieldset>

extension core files:

<?xml version="1.0" encoding="utf-8" ?>
<access component="com_tags">
    <section name="component">
        <action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />
    </section>
</access>

templates:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE install PUBLIC "-//Joomla! 1.6//DTD template 1.0//EN" "http://www.joomla.org/xml/dtd/1.6/template-install.dtd">
<extension version="3.1" type="template" client="site">
</extension>

Should we unify (some of) these?
and isn't the xml version and encoding obligatory?

[META] Finalizing PHPCS 2.x support

Extracted from #109 (comment)

  • In the ruleset.xml there are some pear rules with adjusted messages that we either need to accept messages reporting spaces or will need to create custom copies to properly report the number of tabs.

  • Fix ControlStructuresBrackets sniff issues with the unitTests.

  • Testing against the CMS needs a custom ruleset as a custom standard to mute some errors. The readme has some explanations for adjustments. An example xml file should be included. I also can provide an xml example (code in previous comment way back) and another xml example for projects that have php5.4+ requirements like the Joomla-stats repo (xml code in previous comment just above)

  • Review what our custom sniffs are based on for changes in PHPCS 2.7.x that need to be adopted into our custom sniffs.

  • review for consistency with the old ruleset warnings/errors from phpcs 1.5.x (after the automatic fixers and manual fixes the 1.5.x ruleset should not throw any warnings/errors due to the code style phpcs 2.7.x version being applied. (I've been occasionally running against the CMS admin components for this check, I've only completed PR's for 3 or 4 components)

  • Merge coding standards manual to phpcs-2 branch

Useless method overriding detected

source: Generic.CodeAnalysis.UselessOverridingMethod.Found

If you override a method and change only the parameters, the mentioned error appears. For example:

class A {
    public function Foo($bar = 1)
    { }
}

class B extends A {
    public function Foo($bar = 2)
    {
        parent::Foo($bar);
    }
}

I think that should be fixed for Joomla!

Bad sniff for parenthesis

Getting the following error from the noted sniff:

<error line="147" column="3" severity="error" message="&quot;echo&quot; is a statement not a function; no parentheses are required" source="Joomla.Functions.StatementNotFunction.BracketsNotRequired"/>

The line in question (indentions left in place as exists in the source file):

        echo (new JLayoutFile('install.result', JPATH_ADMINISTRATOR . '/components/com_podcastmanager/layouts'))->render(
            [
                'results' => $results, 'enabled' => $enabled
            ]
        )

InstantiateNewClassesSniff can be simplified

The https://github.com/joomla/coding-standards/blob/master/Sniffs/Classes/InstantiateNewClassesSniff.php sniff is doing a lot of comparisons inside, but if it really checks that no () are present after new SomeClass then why it's not checking that.

  1. find class name, that is created (including namespace)
  2. get next non-whitespace char and if it's not ( then return
  3. get next non-whitespace char and if it's not ) then report an error and return in other case

Escaping \ in strings

The rules for single quoted and double quoted strings differ a bit on the specifics but, in both cases, \\ is an escaped backslash but \ followed by any character that does not need to be escaped is a literal backslash. I think this can easily lead to confusion and I would suggest that the standards should require all backslashes to be escaped whether it is strictly required by PHP or not.

Operator Spacing Sniff Not Ignore Minus Operator in Conditional Statements

$query->bind(':' . count($values), $values[$index], self::getType($v), is_string($v) ? strlen($v) : -1);

Above code throws out following error when running PHPCS using the Joomla coding standards:

Expected 1 space after "-"; 0 found

A temporary solution is to change the code to:

$query->bind(':' . count($values), $values[$index], self::getType($v), is_string($v) ? strlen($v) : (-1));

A previous fix ( http://drupal.org/node/1759346 ) can be used to validate following code properly:

$a = true ? -1 : 1;

However, the fix doesn't work for following code:

$a = true ? 1 : -1;

Remove sniffs in favor of build-in ones

The following sniffs can be removed in favor of one of core PHP_CodeSniffer sniffs, that do the same:

  • ElseIfDeclarationSniff
  • LowerCaseConstantSniff (removed in #101)
  • CastSpacingSniff (removed in #101)
  • SpaceAfterCastSniff (doesn't this conflict with above sniff?)
  • ConcatenationSpacingSniff
  • DisallowSpaceIndentSniff (removed in #101)
  • SuperfluousWhitespaceSniff
  • SemicolonSpacingSniff (removed in #101)

Coding Standard for Coding Standards

Most of the file structures match the source they were copied from, meaning our coding standard files don't even follow our coding standard. On one hand, this makes it a bit easier to follow along with upstream changes, but on the other it's just another inconsistency.

Since we're working on updating everything for PHPCS 2 anyway, any thoughts on tacking onto that TODO list "make coding standard sniffs align with our standard"?

Comments in Control structures

Sometimes putting a comment right inside the control structure is (IMHO) the best place:

// Perform tests
if ($foo
    // Testing phase 1
    && $foo->test1()
    // Testing phase 2
    && $foo->test2())
{
    echo 'True'
}

But code sniffer complains ๐Ÿ˜’

 35 | ERROR | Each line in a multi-line IF statement must begin with a boolean operator

What do you think about adjust the rule?

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.