Skip to content

Commit

Permalink
Handle mocking readonly class
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrooo committed Jun 26, 2023
1 parent d573a35 commit 69dfe8c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/Ouzo/Goodies/Utilities/DynamicProxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,16 @@ private static function getProxyClassDefinition(string $name, string $className)
} else {
$extendsClasses[] = $className;
}

$readonly = '';
if ($reflectionClass->isReadOnly()){
$readonly = 'readonly';
}
$extends = self::generateRelation('extends', $extendsClasses);
$implements = self::generateRelation('implements', $implementsInterfaces);
$code = "class {$name} {$extends} {$implements} {";
$code .= "public \$methodHandler;\n";

$code = "{$readonly} class {$name} {$extends} {$implements} {";
$code .= "public ?object \$methodHandler;\n";
$code .= "function __construct(\$methodHandler) { \$this->methodHandler = \$methodHandler; }\n";
foreach (self::getClassMethods($reflectionClass) as $method) {
$code .= self::generateMethod($method);
Expand Down
14 changes: 13 additions & 1 deletion test/src/Ouzo/Goodies/Utilities/DynamicProxyClassesFor71.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,16 @@ public function fun1(mixed $p1): mixed
{
return $p1;
}
}
}

readonly class ReadonlyClass
{
public function __construct(private string $field)
{
}

public function method():string
{
return $this->field;
}
}
13 changes: 13 additions & 0 deletions test/src/Ouzo/Goodies/Utilities/DynamicProxyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,4 +399,17 @@ public function shouldImplementsMockInterface()
$this->assertTrue($result);
}

#[Test]
public function shouldSedReadonlyClass(): void
{
//given
$testMethodHandler = new TestMethodHandler();
$proxy = DynamicProxy::newInstance(ReadonlyClass::class, $testMethodHandler);

//when
$result = $proxy->method();

//then
$this->assertEquals('TestMethodHandler method', $result);
}
}

0 comments on commit 69dfe8c

Please sign in to comment.