|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PhpSchool\PhpWorkshopTest\Patch; |
| 4 | + |
| 5 | +use PhpParser\Node\Scalar\String_; |
| 6 | +use PhpParser\Node\Stmt\Echo_; |
| 7 | +use PhpParser\ParserFactory; |
| 8 | +use PhpParser\PrettyPrinter\Standard; |
| 9 | +use PhpSchool\PhpWorkshop\Patch\WrapInTryCatch; |
| 10 | +use PHPUnit\Framework\TestCase; |
| 11 | + |
| 12 | +class WrapInTryCatchTest extends TestCase |
| 13 | +{ |
| 14 | + public function testStatementsAreWrappedInTryCatch(): void |
| 15 | + { |
| 16 | + $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
| 17 | + $ast = $parser->parse("<?php echo 'Hello World';"); |
| 18 | + |
| 19 | + $transformer = new WrapInTryCatch(); |
| 20 | + $ast = $transformer->transform($ast); |
| 21 | + |
| 22 | + self::assertSame( |
| 23 | + "try {\n echo 'Hello World';\n} catch (Exception \$e) {\n echo \$e->getMessage();\n}", |
| 24 | + (new Standard())->prettyPrint($ast) |
| 25 | + ); |
| 26 | + } |
| 27 | + |
| 28 | + public function testStatementsAreWrappedInTryCatchWithCustomExceptionClass(): void |
| 29 | + { |
| 30 | + $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
| 31 | + $ast = $parser->parse("<?php echo 'Hello World';"); |
| 32 | + |
| 33 | + $transformer = new WrapInTryCatch(\RuntimeException::class); |
| 34 | + $ast = $transformer->transform($ast); |
| 35 | + |
| 36 | + self::assertSame( |
| 37 | + "try {\n echo 'Hello World';\n} catch (RuntimeException \$e) {\n echo \$e->getMessage();\n}", |
| 38 | + (new Standard())->prettyPrint($ast) |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + public function testStatementsAreWrappedInTryCatchWithStatements(): void |
| 43 | + { |
| 44 | + $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
| 45 | + $ast = $parser->parse("<?php echo 'Hello World';"); |
| 46 | + |
| 47 | + $transformer = new WrapInTryCatch(\RuntimeException::class, [new Echo_([new String_('You caught me!')])]); |
| 48 | + $ast = $transformer->transform($ast); |
| 49 | + |
| 50 | + self::assertSame( |
| 51 | + "try {\n echo 'Hello World';\n} catch (RuntimeException \$e) {\n echo 'You caught me!';\n}", |
| 52 | + (new Standard())->prettyPrint($ast) |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
0 commit comments