Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/duplicated array keys #484

Merged
merged 9 commits into from
Jun 11, 2017
25 changes: 15 additions & 10 deletions src/main/php/PHPMD/Rule/CleanCode/DuplicatedArrayKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
* @link http://phpmd.org/
*/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superfluous line


namespace PHPMD\Rule\CleanCode;

use PDepend\Source\AST\AbstractASTNode;
Expand All @@ -31,16 +30,15 @@
/**
* Duplicated Array Key Rule
*
* This rule detects if array literal has duplicated entries for any key.
* This rule detects duplicated array keys.
*
* @author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
* @author Kamil Szymanaski <kamil.szymanski@gmail.com>
*/
class DuplicatedArrayKey extends AbstractRule implements MethodAware, FunctionAware
{
/**
* This method checks if a given function or method contains an array literal
* with duplicated entries for any key and emits a rule violation if so.
* Retrieves all arrays from single node and performs comparison logic on it
*
* @param AbstractNode $node
* @return void
Expand All @@ -49,17 +47,18 @@ public function apply(AbstractNode $node)
{
foreach ($node->findChildrenOfType('Array') as $arrayNode) {
/** @var ASTNode $arrayNode */
$this->analyzeArray($arrayNode);
$this->checkForDuplicatedArrayKeys($arrayNode);
}
}

/**
* Analyzes single array.
* This method checks if a given function or method contains an array literal
* with duplicated entries for any key and emits a rule violation if so.
*
* @param ASTNode $node Array node.
* @return void
*/
private function analyzeArray(ASTNode $node)
private function checkForDuplicatedArrayKeys(ASTNode $node)
{
$keys = array();
/** @var ASTArrayElement $arrayElement */
Expand All @@ -69,6 +68,7 @@ private function analyzeArray(ASTNode $node)
// skip everything that can't be resolved easily
continue;
}

$key = $arrayElement->getImage();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One white line before

if (isset($keys[$key])) {
$this->addViolation($node, array($key, $arrayElement->getStartLine()));
Expand All @@ -79,14 +79,19 @@ private function analyzeArray(ASTNode $node)
}

/**
* Sets normalized name as node's image.
* To compare keys, we have to cast them to string.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no short description. It should always have a short description and if necessary a long description.

https://www.phpdoc.org/docs/latest/getting-started/your-first-set-of-documentation.html#example

* Non-associative keys have to use index as its key,
* while boolean and nulls have to be casted respectively.
* As current logic doesn't evaluate expressions nor constants,
* statics, globals, etc. we simply skip them.
*
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method could benefit from a longer description, telling the what & why.

* @param AbstractASTNode $node Array key to evaluate.
* @param int $index Fallback in case of non-associative arrays
* @return AbstractASTNode Key name
*/
private function normalizeKey(AbstractASTNode $node, $index)
{
// non-associative - key name equals to its index
if (count($node->getChildren()) === 0) {
$node->setImage((string) $index);
return $node;
Expand All @@ -97,7 +102,7 @@ private function normalizeKey(AbstractASTNode $node, $index)
// skip expressions, method calls, globals and constants
return null;
}
$node->setImage($this->stringFromLiteral($node));
$node->setImage($this->castStringFromLiteral($node));

return $node;
}
Expand All @@ -108,7 +113,7 @@ private function normalizeKey(AbstractASTNode $node, $index)
* @param PDependASTNode $key
* @return string
*/
private function stringFromLiteral(PDependASTNode $key)
private function castStringFromLiteral(PDependASTNode $key)
{
$value = $key->getImage();
switch ($value) {
Expand Down
9 changes: 5 additions & 4 deletions src/main/resources/rulesets/cleancode.xml
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,14 @@ class Foo
</rule>

<rule name="DuplicatedArrayKey"
message="Duplicated array entry for key {0}, first declared at line {1}."
message="Duplicated array key {0}, first declared at line {1}."
class="PHPMD\Rule\CleanCode\DuplicatedArrayKey"
externalInfoUrl="http://phpmd.org/rules/cleancode.html#duplicatedarraykey">
<description>
<![CDATA[
Defining another value for the same key in array literal overrides previous one,
which makes it effectively an unused code. If it's known from the beginning that
the key will have different value, there is usually no point in defining first one.
Defining another value for the same key in an array literal overrides the previous key/value,
which makes it effectively an unused code. If it's known from the beginning that the key
will have different value, there is usually no point in defining first one.
]]>
</description>
<priority>2</priority>
Expand All @@ -149,6 +149,7 @@ function createArray() {
return [
'non-associative 0element', // not applied
0 => 'associative 0-element', // applied
false => 'associative 0-element', // applied
'foo' => 'bar', // not applied
"foo" => 'baz', // applied
];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to see a boolean cast example, e.g. false -> 0.

Expand Down
5 changes: 3 additions & 2 deletions src/site/rst/rules/cleancode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,16 @@ DuplicateArrayKey

Since: PHPMD 2.7.0

Defining another value for the same key in array literal overrides previous one, which makes it effectively an unused code. If it's known from the beginning that the key will have different value, there is usually no point in defining first one.
Defining another value for the same key in an array literal overrides the previous key/value, which makes it effectively an unused code. If it's known from the beginning that the key will have different value, there is usually no point in defining first one.


Example: ::

function createArray() {
return [
'non-associative 0element', // not applied
'non-associative 0-element', // not applied
0 => 'associative 0-element', // applied
false => 'associative 0-element', // applied
'foo' => 'bar', // not applied
"foo" => 'baz', // applied
];
Expand Down
2 changes: 2 additions & 0 deletions src/site/rst/rules/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ Clean Code Rules
- `BooleanArgumentFlag`__: A boolean flag argument is a reliable indicator for a violation of the Single Responsibility Principle (SRP). You can fix this problem by extracting the logic in the boolean flag into its own class or method.
- `ElseExpression`__: An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
- `StaticAccess`__: Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
- `DuplicateArrayKey`__: Defining another value for the same key in an array literal overrides the previous key/value, which makes it effectively an unused code. If it's known from the beginning that the key will have different value, there is usually no point in defining first one.

__ cleancode.html#booleanargumentflag
__ cleancode.html#elseexpression
__ cleancode.html#staticaccess
__ cleancode.html#duplicatearraykey

Code Size Rules
===============
Expand Down
12 changes: 12 additions & 0 deletions src/test/php/PHPMD/Rule/CleanCode/DuplicatedArrayKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,4 +218,16 @@ public function testRuleAppliesCorrectlyWithNestedArrays()
$rule->setReport($this->getReportMock(4));
$rule->apply($this->getFunction());
}

/**
* testRuleAppliesCorrectlyToMultipleArrays
*
* @return void
*/
public function testRuleAppliesCorrectlyToMultipleArrays()
{
$rule = new DuplicatedArrayKey();
$rule->setReport($this->getReportMock(4));
$rule->apply($this->getFunction());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* This file is part of PHP Mess Detector.
*
* Copyright (c) Manuel Pichler <mapi@phpmd.org>.
* All rights reserved.
*
* Licensed under BSD License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright Manuel Pichler. All rights reserved.
* @license https://opensource.org/licenses/bsd-license.php BSD License
* @link http://phpmd.org/
*/

function testRuleAppliesCorrectlyToMultipleArrays()
{
$arrayOne = array(
'foo' => 'bar',
'foo' => 'bar',
);

$arrayTwo = array(
'foo' => 'bar',
);

$arrayThree = array(
'foo' => 'bar',
'foo' => 'bar',
'foo' => 'bar',
);

$arrayFour = array(
'foo' => array(
'foo' => array(
'foo' => 'bar',
'foo' => 'bar',
),
),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class testRuleAppliesWhenKeyIsDeclaredInNonStandardWay extends testRuleAppliesWh
{
const DUPLICATED_KEY = 'foo';

static $classStaticPropertyDuplicate = 'foo';
public static $classStaticPropertyDuplicate = 'foo';

private $classPrivatePropertyDuplicate = 'foo';

Expand All @@ -47,32 +47,33 @@ public function testRuleAppliesWhenKeyIsDeclaredInNonStandardWay()

return array(
// not applied - comment
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add one of the entries below as commented out code.

0 => 'b/ar', // not applied - first occurrence
// 0 => 'bar', // not applied - comment with content
0 => 'bar', // not applied - first occurrence
false => 'bar', // applied - shallow cast to integer 0
1 => 'bar', // not applied - first occurrence
true => 'bar', // applied - shallow cast to integer 1
'' => 'bar', // not applied - first occurrence
null => 'bar', // applied - shallow cast to empty string
'foo' => 'bar', // not applied - first occurrence
'f' . 'o' . 'o' => 'bar', // not applied - resolves in string 'foo' (to be implemented?)
'f' . 'o' . 'o' => 'bar', // not applied - resolves in string 'foo' (not supported yet)
'f' . 'o' . (14 * 1) || 1 . 'o' => 'bar', // not applied - resolves in string 'foo' (to be implemented?)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Not supported yet"

self::DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
parent::DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
static::DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
self::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
parent::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
static::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (to be implemented?)
self::DUPLICATED_KEY => 'bar', // not applied (not supported yet)
parent::DUPLICATED_KEY => 'bar', // not applied (not supported yet)
static::DUPLICATED_KEY => 'bar', // not applied (not supported yet)
self::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (not supported yet)
parent::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (not supported yet)
static::INTERFACE_DUPLICATED_KEY => 'bar', // not applied (not supported yet)
$foo => 'bar', // not applied - resolving variables is impossible in this context
$baz => 'bar', // not applied - see above
$baz => 'bar', // not applied - resolving variables is impossible in this context
$this->getDuplicatedName() => 'bar', // not applied - resolving variable depends on inheritance tree
self::$classStaticPropertyDuplicate => 'bar', // not applied - static property may be modified externally
self::$classPrivateStaticPropertyDuplicate, // not applied - see above
self::$classPrivateStaticPropertyDuplicate, // not applied - static property may be modified externally
$this->classPrivatePropertyDuplicate => 'bar', // not applied - may be modified at any time
$this->classProtectedPropertyDuplicate => 'bar', // not applied - see above
$this->classPublicPropertyDuplicate => 'bar', // not applied - see above
$this->classProtectedPropertyDuplicate => 'bar', // not applied - may be modified at any time
$this->classPublicPropertyDuplicate => 'bar', // not applied - may be modified at any time
global_function_duplicate() => 'bar', // not applied - may be different depending on namespace
GLOBAL_DUPLICATE => 'bar', // not applied - may be different depending on context
"foo" => 'bar', // applied - checkpoint
"foo" => 'bar', // applied - duplicated variable to check if none of above breaks execution
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@

function testRuleNotAppliesToFunctionWithoutArrayDefinition()
{
$foo = 'bar';
$foo .= 'baz';

return $foo;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add some unrelated content.

Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ class testRuleNotAppliesToMethodWithoutArrayDefinition
{
public function testRuleNotAppliesToMethodWithoutArrayDefinition()
{
$someVar = '';
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$someVar = '';

}