Skip to content
This repository has been archived by the owner on Jul 14, 2023. It is now read-only.

Add sniff to disallow unused variables #24

Merged
merged 1 commit into from
Apr 19, 2022

Conversation

aadmathijssen
Copy link
Member

@aadmathijssen aadmathijssen commented Mar 4, 2022

This PR adds the SlevomatCodingStandard.Variables.UnusedVariable sniff, which detects unused variables. See the unusedVariableErrors.php test file for a number of examples that are detected by this tool.

For key/value pairs in a foreach statement where only the key is used, no violation is reported when the value is unused (this required setting the ignoreUnusedValuesWhenOnlyKeysAreUsedInForeach property to true).

So the following file does not generate an error:

<?php

declare(strict_types=1);

function keystoupper(array $values): array
{
    $result = [];
    foreach ($values as $key => $value) {
        $result[] = strtoupper($key);
    }
    return $result;
}

Note that the following still generates an error, because the key is unused:

<?php

declare(strict_types=1);

function strstoupper(array $values): array
{
    $result = [];
    foreach ($values as $key => $value) {
        $result[] = strtoupper($value);
    }
    return $result;
}

The following error is reported:

FILE: /path/to/file.php
----------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------------------------------------
 8 | ERROR | Unused variable $key.
   |       | (SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable)
----------------------------------------------------------------------------------------------------

NB This PR upgrades the Slevomat Coding Standard to v7.0.19, which fixes a few issues in this sniff (#1320 and #1321).

@aadmathijssen aadmathijssen force-pushed the feature/add-unused-variable-sniff branch from 35d19ad to f2c13b1 Compare March 8, 2022 21:44
…uleset.xml`

The `ignoreUnusedValuesWhenOnlyKeysAreUsedInForeach` property is set to true.

This requires an upgrade to v7.0.19 of the Slevomat Coding Standard, which fixes a few issues in this sniff.
@aadmathijssen aadmathijssen force-pushed the feature/add-unused-variable-sniff branch from f2c13b1 to 9edb1f4 Compare March 15, 2022 10:21
@jeroennoten jeroennoten merged commit be3a5a5 into develop Apr 19, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants