Completed
Pull Request — master (#335)
by Juliette
25:48 queued 19:24
created

register()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 8
nop 0
1
<?php
2
/**
3
 * PHPCompatibility_Sniffs_PHP_NewNowdocSniff.
4
 *
5
 * PHP version 5.3
6
 *
7
 * @category  PHP
8
 * @package   PHPCompatibility
9
 * @author    Juliette Reinders Folmer <[email protected]>
10
 */
11
12
/**
13
 * PHPCompatibility_Sniffs_PHP_NewNowdocSniff.
14
 *
15
 * @category  PHP
16
 * @package   PHPCompatibility
17
 * @author    Juliette Reinders Folmer <[email protected]>
18
 */
19
class PHPCompatibility_Sniffs_PHP_NewNowdocSniff extends PHPCompatibility_Sniff
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
20
{
21
22
    /**
23
     * Returns an array of tokens this test wants to listen for.
24
     *
25
     * @return array
26
     */
27
    public function register()
28
    {
29
        $targets = array();
30
31
        if (PHP_VERSION_ID < 50300) {
32
            $targets[] = T_SL;
33
        }
34
35
        if (defined('T_START_NOWDOC')) {
36
            $targets[] = constant('T_START_NOWDOC');
37
        }
38
        if (defined('T_END_NOWDOC')) {
39
            $targets[] = constant('T_END_NOWDOC');
40
        }
41
42
        return $targets;
43
44
    }//end register()
45
46
47
    /**
48
     * Processes this test, when one of its tokens is encountered.
49
     *
50
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
51
     * @param int                  $stackPtr  The position of the current token in
52
     *                                        the stack passed in $tokens.
53
     *
54
     * @return int|void On older PHP versions passes a pointer to the nowdoc closer
55
     *                  to skip passed anything in between in regards to processing
56
     *                  the file for this sniff.
57
     */
58
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
59
    {
60
        if ($this->supportsBelow('5.2') === false) {
61
            return;
62
        }
63
64
        $tokens = $phpcsFile->getTokens();
65
ini_set( 'xdebug.overload_var_dump', 1 );
66
67
static $dumped = false;
68
if($dumped === false) {
69
    echo "\n";
70
    foreach( $tokens as $ptr => $token ) {
71
        echo $ptr . ' :: L' . $token['line'] . ' :: C' . $token['column'] . ' :: ' . $token['type'] . ' :: (' . $token['length'] . ') :: ' . $token['content'] . "\n";
72
//        if ( $token['code'] === T_WHILE || $token['code'] === T_DO || $token['code'] === T_FUNCTION ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73
//            var_dump( $token );
74
//        }
75
    }
76
    unset( $ptr, $token );
77
    $dumped = true;
78
}
79
80
        /*
81
         * In PHP 5.2 the T_NOWDOC tokens aren't recognized yet and PHPCS does not
82
         * backfill for it, so we have to sniff for a specific combination of tokens.
83
         */
84
        if ($tokens[$stackPtr]['code'] === T_SL) {
85 View Code Duplication
            if (isset($tokens[($stackPtr+1)]) === false || $tokens[($stackPtr + 1)]['code'] !== T_LESS_THAN) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                return;
87
            }
88
89 View Code Duplication
            if (isset($tokens[($stackPtr+2)]) === false || $tokens[($stackPtr + 2)]['code'] !== T_CONSTANT_ENCAPSED_STRING) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
                return;
91
            }
92
93
            /*
94
             * Heredoc and nowdoc naming rules:
95
             * "it must contain only alphanumeric characters and underscores and
96
             *  must start with a non-digit character or underscore"
97
             * @link http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
98
             */
99
            if (preg_match('`^\'([a-z][a-z0-9_]*)\'$`iD', $tokens[($stackPtr + 2)]['content'], $matches) < 1) {
100
                return;
101
            }
102
103
            $closer = $phpcsFile->findNext(T_STRING, ($stackPtr + 3), null, false, $matches[1], true);
104
            // The closing identifier must begin in the first column of the line.
105
            if ($closer === false || $tokens[($closer - 1)]['column'] !== 1) {
106
                return;
107
            }
108
109
            // The closing identifier must be the only content on that line, except for maybe a semi-colon.
110
            $next = $phpcsFile->findNext(array(T_WHITESPACE, T_SEMICOLON), ($closer + 1), null, true);
111
            if ($tokens[$closer]['line'] === $tokens[$next]['line']) {
112
                return;
113
            }
114
        }
115
116
        $phpcsFile->addError('Nowdocs are not present in PHP version 5.2 or earlier.', $stackPtr, 'Found');
117
118
        if (isset($closer) !== false) {
119
            $phpcsFile->addError('Nowdocs are not present in PHP version 5.2 or earlier.', $closer, 'Found');
1 ignored issue
show
Bug introduced by
The variable $closer 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...
120
            return ($closer + 1);
121
        }
122
123
    }//end process()
124
125
}//end class
126