Completed
Pull Request — master (#258)
by Enrico
08:55
created

DeprecatedFunctions::getMetadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 0
dl 0
loc 14
ccs 11
cts 11
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace PHPSA\Analyzer\Pass\Expression\FunctionCall;
4
5
use PhpParser\Node\Expr\FuncCall;
6
use PHPSA\Context;
7
use PHPSA\Analyzer\Pass\Metadata;
8
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
9
10
class DeprecatedFunctions extends AbstractFunctionCallAnalyzer
11
{
12
    const DESCRIPTION = 'Checks for use of deprecated functions and gives alternatives if available.';
13
14
    protected $mysql = false;
15
16
    protected $mcrypt = false;
17
18
    protected $map = [];
19
20
    /**
21
     * @param array $config The config values for the analyzer
22
     */
23 1
    public function __construct(array $config)
24
    {
25 1
        if ($config["check_5_3"] == true) {
26
            $check53 = [
27 1
                'define_syslog_variables' => ['5.3','_'],
28 1
                'set_magic_quotes_runtime' => ['5.3','_'],
29 1
                'set_socket_blocking' => ['5.3','_'],
30 1
                'ereg' => ['5.3','preg_match()'],
31 1
                'eregi' => ['5.3','preg_match()'],
32 1
                'ereg_replace' => ['5.3','preg_replace()'],
33 1
                'eregi_replace' => ['5.3','preg_replace()'],
34 1
                'split' => ['5.3','explode()'],
35 1
                'spliti' => ['5.3','preg_split()'],
36 1
                'sql_regcase' => ['5.3','preg_match()'],
37 1
                'session_is_registered' => ['5.3','$_SESSION'],
38 1
                'session_unregister' => ['5.3','$_SESSION'],
39 1
                'session_register' => ['5.3','$_SESSION'],
40 1
            ];
41 1
            $this->map = array_merge($this->map, $check53);
42 1
        }
43
44 1
        if ($config["check_5_5"] == true) {
45
            $check55 = [
0 ignored issues
show
Unused Code introduced by
$check55 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
46 1
                'datefmt_set_timezone_id' => ['5.5','IntlDateFormatter::setTimeZone()'],
47 1
            ];
48 1
            $this->map = array_merge($this->map, $check53);
0 ignored issues
show
Bug introduced by
The variable $check53 does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
49 1
            $this->mysql = true;
50 1
        }
51
        
52 1
        if ($config["check_7_1"] == true) {
53 1
            $this->mcrypt = true;
54 1
        }
55 1
    }
56
57 5
    public function pass(FuncCall $funcCall, Context $context)
58
    {
59 5
        $functionName = $this->resolveFunctionName($funcCall, $context);
60 5
        if ($functionName) {
61 5
            if (isset($this->map[$functionName])) {
62 1
                $context->notice(
63 1
                    'deprecated.function',
64 1
                    sprintf('%s() is deprecated since PHP %s. Use %s instead.', $functionName, $this->map[$functionName][0], $this->map[$functionName][1]),
65
                    $funcCall
66 1
                );
67 5
            } elseif (substr($functionName, 0, 6) === 'mysql_' && $this->mysql) {
68 1
                $context->notice(
69 1
                    'deprecated.function',
70 1
                    sprintf('The MySQL Extension is deprecated since PHP 5.5. Use PDO instead.'),
71
                    $funcCall
72 1
                );
73 5
            } elseif (substr($functionName, 0, 7) === 'mcrypt_' && $this->mcrypt) {
74 1
                $context->notice(
75 1
                    'deprecated.function',
76 1
                    sprintf('The Mcrypt Extension is deprecated since PHP 7.1. Use paragonie/halite instead.'),
77
                    $funcCall
78 1
                );
79 1
            }
80 5
        }
81 5
    }
82
83
    /**
84
     * @return Metadata
85
     */
86 43
    public static function getMetadata()
87
    {
88 43
        $treebuilder = new TreeBuilder();
89 43
        $config = $treebuilder->root("deprecated_functions")
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method canBeDisabled() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
90 43
            ->info(self::DESCRIPTION)
91 43
            ->canBeDisabled()
92 43
            ->children()
93 43
                ->booleanNode("check_5_3")->defaultTrue()->end()
94 43
                ->booleanNode("check_5_5")->defaultTrue()->end()
95 43
                ->booleanNode("check_7_1")->defaultTrue()->end()
96 43
            ->end();
97
98 43
        return new Metadata("deprecated_functions", $config, self::DESCRIPTION);
99
    }
100
}
101