Skip to content

Commit

Permalink
Add sniffs for NOW() and CURRENT_TIMESTAMP()
Browse files Browse the repository at this point in the history
  • Loading branch information
windaishi committed Nov 28, 2024
1 parent 7aeb70a commit 1bee062
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
namespace VIISON\StyleGuide\PHPCS\Standards\VIISON\Sniffs\Strings;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

/**
* This sniff disallows the usage of the method NOW() and CURRENT_TIMESTAMP() in SQL queries as they have weird
* timezone behavior. It suggests using UTC_TIMESTAMP() instead.
*/
class NoNowInMySqlSniff implements Sniff
{
/**
* @inheritdoc
*/
public function register()
{
return [
T_CONSTANT_ENCAPSED_STRING,
T_HEREDOC,
T_NOWDOC,
];
}

/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$token = $phpcsFile->getTokens()[$stackPtr];
$content = $token['content'];

if (stripos($content, 'NOW(') !== false) {
$error = 'The usage of the method NOW() in SQL queries is not allowed. Use UTC_TIMESTAMP() instead.';
$phpcsFile->addError($error, $stackPtr, 'NoNowInSql');
}

if (stripos($content, 'CURRENT_TIMESTAMP(') !== false) {
$error = 'The usage of the method CURRENT_TIMESTAMP() in SQL queries is not allowed. Use UTC_TIMESTAMP() instead.';
$phpcsFile->addError($error, $stackPtr, 'NoCurrentTimestampInSql');
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
namespace VIISON\StyleGuide\PHPCS\Standards\VIISON\Sniffs\Strings;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

/**
* This sniff checks for the usage of 'UTC_TIMESTAMP()' in string literals and suggests passing 3 as an argument.
*/
class NoUtcTimestampWithoutArgumentInMySqlSniff implements Sniff
{
/**
* @inheritdoc
*/
public function register()
{
return [
T_CONSTANT_ENCAPSED_STRING,
T_HEREDOC,
T_NOWDOC
];
}

/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$token = $phpcsFile->getTokens()[$stackPtr];
$content = $token['content'];

if (preg_match('/UTC_TIMESTAMP\(\s*?[012456789]?\s*?\)/', $content)) {
$error = 'Always pass 3 as an argument for UTC_TIMESTAMP() to ensure a consistent precision.';
$phpcsFile->addError($error, $stackPtr, 'FoundNowFunction');
}
}
}

0 comments on commit 1bee062

Please sign in to comment.