|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace IxDFCodingStandard\Sniffs\Classes; |
| 4 | + |
| 5 | +use IxDFCodingStandard\Sniffs\Classes\data\ForbidMethodDeclarationSniff\ForbiddenParent; |
| 6 | +use IxDFCodingStandard\TestCase; |
| 7 | +use PHPUnit\Framework\Attributes\CoversClass; |
| 8 | +use PHPUnit\Framework\Attributes\RequiresPhp; |
| 9 | +use PHPUnit\Framework\Attributes\Test; |
| 10 | + |
| 11 | +#[CoversClass(ForbidMethodDeclarationSniff::class)] |
| 12 | +final class ForbidMethodDeclarationSniffTest extends TestCase |
| 13 | +{ |
| 14 | + private const FORBIDDEN_METHODS = [ |
| 15 | + ForbiddenParent::class.'::shouldSend' => '\App\Notifications\Support\ShouldCheckConditionsBeforeSendingOut::shouldBeSent', |
| 16 | + ]; |
| 17 | + |
| 18 | + #[Test] |
| 19 | + #[RequiresPhp('>= 8.5.0')] |
| 20 | + public function it_reports_forbidden_method_even_when_the_class_uses_a_deprecated_trait(): void |
| 21 | + { |
| 22 | + // #[\Deprecated] is only allowed on traits since PHP 8.5 (earlier versions reject the fixture at compile time). |
| 23 | + // Resolving the class autoloads it; using a deprecated trait then emits a deprecation, and the sniff must |
| 24 | + // silence it instead of letting it abort the whole file check (Internal.Exception). |
| 25 | + $deprecations = []; |
| 26 | + set_error_handler( |
| 27 | + static function (int $errno, string $message) use (&$deprecations): bool { |
| 28 | + $deprecations[] = $message; |
| 29 | + |
| 30 | + return true; |
| 31 | + }, |
| 32 | + \E_DEPRECATED | \E_USER_DEPRECATED |
| 33 | + ); |
| 34 | + |
| 35 | + try { |
| 36 | + $report = self::checkFile( |
| 37 | + __DIR__.'/data/ForbidMethodDeclarationSniff/ChildDeclaringForbiddenMethod.php', |
| 38 | + ['forbiddenMethods' => self::FORBIDDEN_METHODS] |
| 39 | + ); |
| 40 | + } finally { |
| 41 | + restore_error_handler(); |
| 42 | + } |
| 43 | + |
| 44 | + self::assertSame([], $deprecations, 'The sniff must not leak deprecations triggered while autoloading the analysed class.'); |
| 45 | + self::assertSame(1, $report->getErrorCount()); |
| 46 | + self::assertSniffError($report, 5, ForbidMethodDeclarationSniff::FORBIDDEN_METHOD_DECLARATION); |
| 47 | + } |
| 48 | + |
| 49 | + #[Test] |
| 50 | + public function it_does_not_report_when_the_subclass_does_not_declare_the_forbidden_method(): void |
| 51 | + { |
| 52 | + $report = self::checkFile( |
| 53 | + __DIR__.'/data/ForbidMethodDeclarationSniff/ChildWithoutForbiddenMethod.php', |
| 54 | + ['forbiddenMethods' => self::FORBIDDEN_METHODS] |
| 55 | + ); |
| 56 | + |
| 57 | + self::assertNoSniffErrorInFile($report); |
| 58 | + } |
| 59 | +} |
0 commit comments