Skip to content

Commit

Permalink
Add sniff to disallow alternative PHP open tags.
Browse files Browse the repository at this point in the history
This sniff checks  for the alternative PHP syntaxes - ASP tags and script tags - which have been removed in PHP7:
```php
<% echo 'content'; %>
<%= 'content'; %>
<script language="php">
echo 'content';
</script>
```
Ref: http://php.net/manual/en/language.basic-syntax.phptags.php

If PHPCS is run on PHP < 7, the script tags will be fixable, provided they are correct.
If PHPCS is run on PHP < 7 + asp_tags is on, the ASP tags will be fixable.

Fixes squizlabs#1063

Similar to squizlabs#1069, the `myconfig5.ini` and `myconfig57.ini` files and the adjustment to the travis script are needed for the fixer unit tests to pass as when asp_tags is set to off, the fixer won't fix it correctly and the tests will fail ;-)
  • Loading branch information
jrfnl committed Jul 28, 2016
1 parent cd29ed2 commit 2113732
Show file tree
Hide file tree
Showing 11 changed files with 440 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ php:
- hhvm

before_script:
- if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then phpenv config-add myconfig.ini; fi
- if [[ $TRAVIS_PHP_VERSION != "7.0" && $TRAVIS_PHP_VERSION != "nightly" && $TRAVIS_PHP_VERSION != "hhvm" ]]; then mv -f myconfig5.ini myconfig.ini; phpenv config-add myconfig.ini; fi
- if [[ $TRAVIS_PHP_VERSION == "7.0" || $TRAVIS_PHP_VERSION == "nightly" ]]; then mv -f myconfig57.ini myconfig.ini; phpenv config-add myconfig.ini; fi

script:
- if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then php scripts/phpcs --config-set php_path php; fi
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<documentation title="Alternative PHP Code Tags">
<standard>
<![CDATA[
Always use <?php ?> to delimit PHP code, do not use the ASP <% %> style tags nor the <script language="php"></script> tags. This is the most portable way to include PHP code on differing operating systems and setups.
]]>
</standard>
</documentation>
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
<?php
/**
* Generic_Sniffs_PHP_DisallowAlternativePHPTagsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/

/**
* Generic_Sniffs_PHP_DisallowAlternativePHPTagsSniff.
*
* Verifies that no alternative PHP tags are used.
*
* If alternative PHP open tags are found, this sniff can fix both the open and close tags.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_DisallowAlternativePHPTagsSniff implements PHP_CodeSniffer_Sniff
{


/**
* Whether ASP tags are enabled or not.
*
* @var bool
*/
private $_aspTags = false;


/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
if (PHP_VERSION_ID < 70000) {
$this->_aspTags = (boolean) ini_get('asp_tags');
}

return array(
T_OPEN_TAG,
T_OPEN_TAG_WITH_ECHO,
T_INLINE_HTML,
);

}//end register()


/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$openTag = $tokens[$stackPtr];
$content = $openTag['content'];

if (trim($content) === '') {
return;
}

if (T_OPEN_TAG === $openTag['code']) {
if ('<%' === $content) {
$error = 'ASP style opening tag used; expected "<?php" but found "%s"';
$closer = $this->findClosingTag($phpcsFile, $tokens, $stackPtr, '%>');
$error_id = 'ASPOpenTagFound';
} else if (false !== strpos($content, '<script ')) {
$error = 'Script style opening tag used; expected "<?php" but found "%s"';
$closer = $this->findClosingTag($phpcsFile, $tokens, $stackPtr, '</script>');
$error_id = 'ScriptOpenTagFound';
}

if (isset($error, $closer, $error_id) === true) {
$data = array($content);

if (false === $closer) {
$phpcsFile->addError($error, $stackPtr, $error_id, $data);
} else {
$fix = $phpcsFile->addFixableError($error, $stackPtr, $error_id, $data);
if (true === $fix) {
$this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer);
}
}
}

return;
}//end if

if (T_OPEN_TAG_WITH_ECHO === $openTag['code'] && '<%=' === $content) {
$error = 'ASP style opening tag used with echo; expected "<?php echo %s ..." but found "%s %s ..."';
$nextVar = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
$snippet = $this->getSnippet($tokens[$nextVar]['content']);
$data = array(
$snippet,
$content,
$snippet,
);

$closer = $this->findClosingTag($phpcsFile, $tokens, $stackPtr, '%>');

if (false === $closer) {
$phpcsFile->addError($error, $stackPtr, 'ASPShortOpenTagFound', $data);
} else {
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'ASPShortOpenTagFound', $data);
if (true === $fix) {
$this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer, true);
}
}

return;
}//end if

// Account for incorrect script open tags. The "(?:<s)?" in the regex is to work-around a bug in PHP 5.2.
if (T_INLINE_HTML === $openTag['code'] && 1 === preg_match('`((?:<s)?cript (?:[^>]+)?language=[\'"]?php[\'"]?(?:[^>]+)?>)`i', $content, $match)) {
$error = 'Script style opening tag used; expected "<?php" but found "%s"';
$snippet = $this->getSnippet($content, $match[1]);
$data = array($match[1].$snippet);

$phpcsFile->addError($error, $stackPtr, 'ScriptOpenTagFound', $data);

return;
}

if (T_INLINE_HTML === $openTag['code'] && false === $this->_aspTags) {
if (false !== strpos($content, '<%=')) {
$error = 'Possible use of ASP style short opening tags detected. Needs manual inspection. Found: %s';
$snippet = $this->getSnippet($content, '<%=');
$data = array('<%='.$snippet);

$phpcsFile->addWarning($error, $stackPtr, 'MaybeASPShortOpenTagFound', $data);
} else if (false !== strpos($content, '<%')) {
$error = 'Possible use of ASP style opening tags detected. Needs manual inspection. Found: %s';
$snippet = $this->getSnippet($content, '<%');
$data = array('<%'.$snippet);

$phpcsFile->addWarning($error, $stackPtr, 'MaybeASPOpenTagFound', $data);
}
}

}//end process()


/**
* Get a snippet from a HTML token.
*
* @param string $content The content of the HTML token.
* @param string $start_at Partial string to use as a starting point for the snippet.
* @param int $length The target length of the snippet to get. Defaults to 40.
*
* @return string
*/
protected function getSnippet($content, $start_at = '', $length = 40)
{
$start_pos = 0;

if ($start_at !== '') {
$start_pos = strpos($content, $start_at);
if ($start_pos !== false) {
$start_pos += strlen($start_at);
}
}

$snippet = substr($content, $start_pos, $length);
if ((strlen($content) - $start_pos) > $length) {
$snippet .= '...';
}

return $snippet;

}//end getSnippet()


/**
* Try and find a matching PHP closing tag.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param array $tokens The token stack.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $content The expected content of the closing tag to match the opener.
*
* @return int|false Pointer to the position in the stack for the closing tag or false if not found.
*/
protected function findClosingTag(PHP_CodeSniffer_File $phpcsFile, $tokens, $stackPtr, $content)
{
$closer = $phpcsFile->findNext(T_CLOSE_TAG, ($stackPtr + 1));

if ($closer !== false && $content === trim($tokens[$closer]['content'])) {
return $closer;
}

return false;

}//end findClosingTag()


/**
* Add a changeset to replace the alternative PHP tags.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param array $tokens The token stack.
* @param int $open_tag_pointer Stack pointer to the PHP open tag.
* @param int $close_tag_pointer Stack pointer to the PHP close tag.
* @param bool $echo Whether to add 'echo' or not.
*
* @return void
*/
protected function addChangeset(PHP_CodeSniffer_File $phpcsFile, $tokens, $open_tag_pointer, $close_tag_pointer, $echo = false)
{
// Build up the open tag replacement and make sure there's always whitespace behind it.
$open_replacement = '<?php';
if ($echo === true) {
$open_replacement .= ' echo';
}

if ($tokens[($open_tag_pointer + 1)]['code'] !== T_WHITESPACE) {
$open_replacement .= ' ';
}

// Make sure we don't remove any line breaks after the closing tag.
$regex = '`'.preg_quote(trim($tokens[$close_tag_pointer]['content'])).'`';
$close_replacement = preg_replace($regex, '?>', $tokens[$close_tag_pointer]['content']);

$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($open_tag_pointer, $open_replacement);
$phpcsFile->fixer->replaceToken($close_tag_pointer, $close_replacement);
$phpcsFile->fixer->endChangeset();

}//end addChangeset()


}//end class
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<div>
<?php echo $var; ?>
Some content here.
<script language="php">
echo $var;
</script>
<script language='php'>echo $var;</script>
<script type="text/php" language="php">
echo $var;
</script>
<script language='PHP' type='text/php'>
echo $var;
</script>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<div>
<?php echo $var; ?>
Some content here.
<?php
echo $var;
?>
<?php echo $var;?>
<script type="text/php" language="php">
echo $var;
</script>
<script language='PHP' type='text/php'>
echo $var;
</script>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<div>
<% echo $var; %>
<p>Some text <% echo $var; %> and some more text</p>
<%= $var . ' and some more text to make sure the snippet works'; %>
<p>Some text <%= $var %> and some more text</p>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<div>
<?php echo $var; ?>
<p>Some text <?php echo $var; ?> and some more text</p>
<?php echo $var . ' and some more text to make sure the snippet works'; ?>
<p>Some text <?php echo $var ?> and some more text</p>
</div>
Loading

0 comments on commit 2113732

Please sign in to comment.