Skip to content

Commit a178a71

Browse files
committed
Add support for Transformer instances
1 parent 0c06899 commit a178a71

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/CodePatcher.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use PhpParser\PrettyPrinter\Standard;
1212
use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
1313
use PhpSchool\PhpWorkshop\Exercise\SubmissionPatchable;
14+
use PhpSchool\PhpWorkshop\Patch\Transformer;
1415

1516
/**
1617
* Service to apply patches to a student's solution. Accepts a default patch via the constructor.
@@ -102,10 +103,15 @@ private function applyPatch(Patch $patch, string $code): string
102103
continue;
103104
}
104105

105-
if (is_callable($modifier)) {
106+
if ($modifier instanceof \Closure) {
106107
$statements = $modifier($statements);
107108
continue;
108109
}
110+
111+
if ($modifier instanceof Transformer) {
112+
$statements = $modifier->transform($statements);
113+
continue;
114+
}
109115
}
110116

111117
if ($declare !== null && !$this->isFirstStatementStrictTypesDeclare($statements)) {

test/CodePatcherTest.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ public function codeProvider(): array
9595
(new Patch())->withInsertion(new Insertion(Insertion::TYPE_BEFORE, ' <?php $before = "here";')),
9696
"<?php\n\n\$before = \"here\";\n\$original = true;"
9797
],
98-
'transformer' => [
98+
'transformer-closure' => [
9999
'<?php $original = true;',
100100
(new Patch())
101101
->withTransformer(function (array $statements) {
@@ -122,6 +122,22 @@ public function codeProvider(): array
122122
}),
123123
"<?php\n\ntry {\n \$before = \"here\";\n \$original = true;\n} catch (Exception \$e) {\n}"
124124
],
125+
'transformer-class' => [
126+
'<?php $original = true;',
127+
(new Patch())
128+
->withTransformer(new class implements Patch\Transformer {
129+
public function transform(array $statements): array
130+
{
131+
return [
132+
new TryCatch(
133+
$statements,
134+
[new Catch_([new Name(\Exception::class)], new Variable('e'), [])]
135+
)
136+
];
137+
}
138+
}),
139+
"<?php\n\ntry {\n \$original = true;\n} catch (Exception \$e) {\n}"
140+
],
125141
];
126142
}
127143

0 commit comments

Comments
 (0)