|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Okapi\CodeTransformer\Tests\Functional; |
| 4 | + |
| 5 | +use Okapi\CodeTransformer\Tests\ClassLoaderMockTrait; |
| 6 | +use Okapi\CodeTransformer\Tests\Stubs\ClassesToTransform\ChangedClass; |
| 7 | +use Okapi\CodeTransformer\Tests\Stubs\Kernel\ApplicationKernel; |
| 8 | +use Okapi\CodeTransformer\Tests\Util; |
| 9 | +use Okapi\Filesystem\Filesystem; |
| 10 | +use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; |
| 11 | +use PHPUnit\Framework\TestCase; |
| 12 | +use Throwable; |
| 13 | + |
| 14 | +#[RunTestsInSeparateProcesses] |
| 15 | +class ChangedClassTest extends TestCase |
| 16 | +{ |
| 17 | + use ClassLoaderMockTrait; |
| 18 | + |
| 19 | + private static string $classFileContent; |
| 20 | + |
| 21 | + public function testChangedClass(): void |
| 22 | + { |
| 23 | + Util::clearCache(); |
| 24 | + ApplicationKernel::init(); |
| 25 | + |
| 26 | + $class = ChangedClass::class; |
| 27 | + $this->assertWillBeTransformed($class); |
| 28 | + |
| 29 | + $changedClass = new $class(); |
| 30 | + $this->assertSame( |
| 31 | + 'Hello World from Code Transformer!', |
| 32 | + $changedClass->test(), |
| 33 | + ); |
| 34 | + |
| 35 | + // Change class |
| 36 | + $classFilePath = Util::CLASSES_TO_TRANSFORM_DIR . '/ChangedClass.php'; |
| 37 | + $classFileContent = Filesystem::readFile($classFilePath); |
| 38 | + $tmpPath = Util::TMP_DIR . '/ChangedClass.php'; |
| 39 | + Filesystem::writeFile($tmpPath, $classFileContent); |
| 40 | + |
| 41 | + $changedFileContent = str_replace( |
| 42 | + 'Hello World!', |
| 43 | + 'Hello Changed World!', |
| 44 | + $classFileContent, |
| 45 | + ); |
| 46 | + |
| 47 | + sleep(1); |
| 48 | + Filesystem::writeFile($classFilePath, $changedFileContent); |
| 49 | + } |
| 50 | + |
| 51 | + public function testCachedChangedClass(): void |
| 52 | + { |
| 53 | + $exception = null; |
| 54 | + try { |
| 55 | + ApplicationKernel::init(); |
| 56 | + |
| 57 | + $class = ChangedClass::class; |
| 58 | + $this->assertWillBeTransformed($class); |
| 59 | + |
| 60 | + $classInstance = new $class(); |
| 61 | + $this->assertSame( |
| 62 | + 'Hello Changed World from Code Transformer!', |
| 63 | + $classInstance->test(), |
| 64 | + ); |
| 65 | + } catch (Throwable $e) { |
| 66 | + $exception = $e; |
| 67 | + } |
| 68 | + |
| 69 | + // Restore class |
| 70 | + $tmpPath = Util::TMP_DIR . '/ChangedClass.php'; |
| 71 | + if (!file_exists($tmpPath)) { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + $tmpFileContent = Filesystem::readFile($tmpPath); |
| 76 | + $classFilePath = Util::CLASSES_TO_TRANSFORM_DIR . '/ChangedClass.php'; |
| 77 | + |
| 78 | + Filesystem::writeFile($classFilePath, $tmpFileContent); |
| 79 | + |
| 80 | + if ($exception !== null) { |
| 81 | + /** @noinspection PhpUnhandledExceptionInspection */ |
| 82 | + throw $exception; |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments