Skip to content

Commit 8e10722

Browse files
committed
Add custom NoTopLevelDefineSniff sniff
1 parent 5c92ab8 commit 8e10722

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php declare(strict_types=1); # -*- coding: utf-8 -*-
2+
/*
3+
* This file is part of the php-coding-standards package.
4+
*
5+
* (c) Inpsyde GmbH
6+
*
7+
* For the full copyright and license information, please view the LICENSE
8+
* file that was distributed with this source code.
9+
*/
10+
11+
namespace Inpsyde\InpsydeCodingStandard\Sniffs\CodeQuality;
12+
13+
use Inpsyde\InpsydeCodingStandard\Helpers;
14+
use PHP_CodeSniffer\Files\File;
15+
use PHP_CodeSniffer\Sniffs\Sniff;
16+
17+
/**
18+
* @package php-coding-standards
19+
* @license http://opensource.org/licenses/MIT MIT
20+
*/
21+
final class NoTopLevelDefineSniff implements Sniff
22+
{
23+
/**
24+
* @return int[]
25+
*/
26+
public function register()
27+
{
28+
return [T_STRING];
29+
}
30+
31+
/**
32+
* @param File $file
33+
* @param int $position
34+
*/
35+
public function process(File $file, $position)
36+
{
37+
$token = $file->getTokens()[$position];
38+
39+
if (($token['content'] ?? '') !== 'define'
40+
|| ($token['level'] ?? -1) !== 0
41+
|| !Helpers::isFunctionCall($file, $position)
42+
) {
43+
return;
44+
}
45+
46+
$file->addWarning(
47+
'Do not use "define" for top-level constant definition. Prefer "const" instead.',
48+
$position,
49+
'Found'
50+
);
51+
}
52+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Inpsyde\InpsydeCodingStandard\Tests\Fixtures;
4+
5+
// @phpcsSniff CodeQuality.NoTopLevelDefine
6+
7+
if (!defined('X')) {
8+
define('X', 1);
9+
}
10+
11+
if (false) {
12+
define('Y', 1);
13+
}
14+
15+
// @phpcsWarningOnNextLine
16+
define('Z', 1);
17+
18+
const ZZZ = 1;

0 commit comments

Comments
 (0)