|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PixelFederation\CodingStandards\Tests\Functional; |
| 6 | + |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | + |
| 9 | +abstract class PhpcsTestCase extends TestCase |
| 10 | +{ |
| 11 | + public static function assertPhpcbf( |
| 12 | + string $fileBefore, |
| 13 | + string $fileAfter, |
| 14 | + string $message = '', |
| 15 | + string $tmpFilename = 'Bar.php', |
| 16 | + ): void { |
| 17 | + $before = __DIR__ . '/' . $fileBefore; |
| 18 | + $expected = __DIR__ . '/' . $fileAfter; |
| 19 | + |
| 20 | + self::assertFileExists($before, 'Before file does not exist: ' . $before); |
| 21 | + self::assertFileExists($expected, 'After file does not exist: ' . $expected); |
| 22 | + |
| 23 | + $tmpDir = sys_get_temp_dir() . '/cs_bar_' . bin2hex(random_bytes(4)); |
| 24 | + self::assertTrue(mkdir($tmpDir, 0777, true), $message); |
| 25 | + |
| 26 | + $tmpFile = $tmpDir . '/' . $tmpFilename; |
| 27 | + self::assertNotFalse($tmpFile, $message); |
| 28 | + file_put_contents($tmpFile, file_get_contents($before)); |
| 29 | + |
| 30 | + $cmdCbf = sprintf( |
| 31 | + '%s --standard=%s %s 2>&1', |
| 32 | + escapeshellarg(self::getPath('PATH_PHPCBF')), |
| 33 | + escapeshellarg(self::getPath('PATH_PHPCS_RULESET')), |
| 34 | + escapeshellarg($tmpFile), |
| 35 | + ); |
| 36 | + |
| 37 | + $beforeContent = file_get_contents($before); |
| 38 | + file_put_contents($tmpFile, $beforeContent); |
| 39 | + |
| 40 | + exec($cmdCbf, $outputCbf, $exitCodeCbf); |
| 41 | + self::assertSame(0, $exitCodeCbf, $message); |
| 42 | + |
| 43 | + $actual = file_get_contents($tmpFile); |
| 44 | + self::assertNotSame( |
| 45 | + $beforeContent, |
| 46 | + $actual, |
| 47 | + 'Expected PHPCBF to change the file, but contents are identical.' . $message, |
| 48 | + ); |
| 49 | + |
| 50 | + self::assertSame( |
| 51 | + file_get_contents($expected), |
| 52 | + $actual, |
| 53 | + "PHPCBF output does not match expected 'after' file. " . $message, |
| 54 | + ); |
| 55 | + |
| 56 | + $cmdCs = sprintf( |
| 57 | + '%s --standard=%s %s 2>&1', |
| 58 | + escapeshellarg(self::getPath('PATH_PHPCS')), |
| 59 | + escapeshellarg(self::getPath('PATH_PHPCS_RULESET')), |
| 60 | + escapeshellarg($tmpFile), |
| 61 | + ); |
| 62 | + |
| 63 | + exec($cmdCs, $outputCs, $exitCodeCs); |
| 64 | + |
| 65 | + self::assertSame( |
| 66 | + 0, |
| 67 | + $exitCodeCs, |
| 68 | + sprintf( |
| 69 | + "Expected no PHPCS errors after PHPCBF fix, got exit code %s.\nOutput:\n%s %s", |
| 70 | + $exitCodeCs, |
| 71 | + implode("\n", $outputCs), |
| 72 | + $message, |
| 73 | + ), |
| 74 | + ); |
| 75 | + |
| 76 | + @unlink($tmpFile); |
| 77 | + } |
| 78 | + |
| 79 | + protected static function getPath(string $env): string |
| 80 | + { |
| 81 | + return __DIR__ . '/../../' . getenv($env); |
| 82 | + } |
| 83 | +} |
0 commit comments