Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/PropertyGarbageCollection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace Lendable\PHPUnitExtensions;

use PHPUnit\Framework\Attributes\After;
use PHPUnit\Framework\TestCase;

/**
* @mixin TestCase
*/
trait PropertyGarbageCollection
{
#[After]
final protected function unsetAllProperties(): void
{
$reflection = new \ReflectionObject($this);

foreach ($reflection->getProperties() as $property) {
if ($property->isStatic() || \str_starts_with($property->getDeclaringClass()->getName(), 'PHPUnit\\')) {
continue;
}

unset($this->{$property->getName()}); // @phpstan-ignore-line
}

while (($parent = $reflection->getParentClass()) !== false) {
if (\str_starts_with($parent->getName(), 'PHPUnit\\')) {
break;
}

foreach ($parent->getProperties() as $property) {
if ($property->isStatic() || \str_starts_with($property->getDeclaringClass()->getName(), 'PHPUnit\\')) {
continue;
}

(function () use ($property): void {
unset($this->{$property->getName()}); // @phpstan-ignore-line
})->bindTo($this, $parent->getName())->call($this);
}
}

\gc_collect_cycles();
}
}
1 change: 1 addition & 0 deletions src/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
abstract class TestCase extends PHPUnitTestCase
{
use StrictMocking;
use PropertyGarbageCollection;
}