From 315d39ae68d2397aec8e125368f5d8aed4d11bf5 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Tue, 22 Jun 2021 18:04:03 +0100 Subject: [PATCH] Wrap in try/catch patch --- src/Patch/WrapInTryCatch.php | 58 +++++++++++++++++++++++++++++++ test/Patch/WrapInTryCatchTest.php | 55 +++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 src/Patch/WrapInTryCatch.php create mode 100644 test/Patch/WrapInTryCatchTest.php 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) + ); + } +}