Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add property garbage collection #76

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
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;
}
Loading