diff --git a/src/Patch/WrapInTryCatch.php b/src/Patch/WrapInTryCatch.php new file mode 100644 index 00000000..c3d86428 --- /dev/null +++ b/src/Patch/WrapInTryCatch.php @@ -0,0 +1,58 @@ + + */ + private $statements; + + /** + * @param string $exceptionClass + * @param array|null $statements + */ + public function __construct(string $exceptionClass = \Exception::class, array $statements = null) + { + $this->exceptionClass = $exceptionClass; + $this->statements = $statements ?: [ + new Echo_([ + new MethodCall(new Variable('e'), 'getMessage') + ]) + ]; + } + + /** + * @param array $statements + * @return array + */ + public function transform(array $statements): array + { + return [ + new TryCatch( + $statements, + [ + new Catch_( + [new Name($this->exceptionClass)], + new Variable('e'), + $this->statements + ) + ] + ) + ]; + } +} diff --git a/test/Patch/WrapInTryCatchTest.php b/test/Patch/WrapInTryCatchTest.php new file mode 100644 index 00000000..a25773d2 --- /dev/null +++ b/test/Patch/WrapInTryCatchTest.php @@ -0,0 +1,55 @@ +create(ParserFactory::PREFER_PHP7); + $ast = $parser->parse("transform($ast); + + self::assertSame( + "try {\n echo 'Hello World';\n} catch (Exception \$e) {\n echo \$e->getMessage();\n}", + (new Standard())->prettyPrint($ast) + ); + } + + public function testStatementsAreWrappedInTryCatchWithCustomExceptionClass(): void + { + $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); + $ast = $parser->parse("transform($ast); + + self::assertSame( + "try {\n echo 'Hello World';\n} catch (RuntimeException \$e) {\n echo \$e->getMessage();\n}", + (new Standard())->prettyPrint($ast) + ); + } + + public function testStatementsAreWrappedInTryCatchWithStatements(): void + { + $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); + $ast = $parser->parse("transform($ast); + + self::assertSame( + "try {\n echo 'Hello World';\n} catch (RuntimeException \$e) {\n echo 'You caught me!';\n}", + (new Standard())->prettyPrint($ast) + ); + } +}