Skip to content

Commit 1bee062

Browse files
committed
Add sniffs for NOW() and CURRENT_TIMESTAMP()
1 parent 7aeb70a commit 1bee062

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
namespace VIISON\StyleGuide\PHPCS\Standards\VIISON\Sniffs\Strings;
3+
4+
use PHP_CodeSniffer\Files\File;
5+
use PHP_CodeSniffer\Sniffs\Sniff;
6+
7+
/**
8+
* This sniff disallows the usage of the method NOW() and CURRENT_TIMESTAMP() in SQL queries as they have weird
9+
* timezone behavior. It suggests using UTC_TIMESTAMP() instead.
10+
*/
11+
class NoNowInMySqlSniff implements Sniff
12+
{
13+
/**
14+
* @inheritdoc
15+
*/
16+
public function register()
17+
{
18+
return [
19+
T_CONSTANT_ENCAPSED_STRING,
20+
T_HEREDOC,
21+
T_NOWDOC,
22+
];
23+
}
24+
25+
/**
26+
* @inheritdoc
27+
*/
28+
public function process(File $phpcsFile, $stackPtr)
29+
{
30+
$token = $phpcsFile->getTokens()[$stackPtr];
31+
$content = $token['content'];
32+
33+
if (stripos($content, 'NOW(') !== false) {
34+
$error = 'The usage of the method NOW() in SQL queries is not allowed. Use UTC_TIMESTAMP() instead.';
35+
$phpcsFile->addError($error, $stackPtr, 'NoNowInSql');
36+
}
37+
38+
if (stripos($content, 'CURRENT_TIMESTAMP(') !== false) {
39+
$error = 'The usage of the method CURRENT_TIMESTAMP() in SQL queries is not allowed. Use UTC_TIMESTAMP() instead.';
40+
$phpcsFile->addError($error, $stackPtr, 'NoCurrentTimestampInSql');
41+
}
42+
}
43+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
namespace VIISON\StyleGuide\PHPCS\Standards\VIISON\Sniffs\Strings;
3+
4+
use PHP_CodeSniffer\Files\File;
5+
use PHP_CodeSniffer\Sniffs\Sniff;
6+
7+
/**
8+
* This sniff checks for the usage of 'UTC_TIMESTAMP()' in string literals and suggests passing 3 as an argument.
9+
*/
10+
class NoUtcTimestampWithoutArgumentInMySqlSniff implements Sniff
11+
{
12+
/**
13+
* @inheritdoc
14+
*/
15+
public function register()
16+
{
17+
return [
18+
T_CONSTANT_ENCAPSED_STRING,
19+
T_HEREDOC,
20+
T_NOWDOC
21+
];
22+
}
23+
24+
/**
25+
* @inheritdoc
26+
*/
27+
public function process(File $phpcsFile, $stackPtr)
28+
{
29+
$token = $phpcsFile->getTokens()[$stackPtr];
30+
$content = $token['content'];
31+
32+
if (preg_match('/UTC_TIMESTAMP\(\s*?[012456789]?\s*?\)/', $content)) {
33+
$error = 'Always pass 3 as an argument for UTC_TIMESTAMP() to ensure a consistent precision.';
34+
$phpcsFile->addError($error, $stackPtr, 'FoundNowFunction');
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)