Created
June 20, 2017 15:59
-
-
Save enumag/26b49b14ac50069db8b402b4c3b3789d to your computer and use it in GitHub Desktop.
MemoryListener for PHPUnit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Tests\Listener; | |
use PHPUnit\Framework\BaseTestListener; | |
use PHPUnit\Framework\Test; | |
class MemoryListener extends BaseTestListener | |
{ | |
private const PHPUNIT_PROPERTY_PREFIX = 'PHPUnit_'; | |
public function endTest(Test $test, $time) | |
{ | |
$testReflection = new \ReflectionObject($test); | |
$this->safelyFreeProperties($test, $testReflection->getProperties()); | |
} | |
private function safelyFreeProperties(Test $test, array $properties) | |
{ | |
foreach ($properties as $property) { | |
if ($this->isSafeToFreeProperty($property)) { | |
$this->freeProperty($test, $property); | |
} | |
} | |
} | |
private function isSafeToFreeProperty(\ReflectionProperty $property) | |
{ | |
return ! $property->isStatic() && $this->isNotPhpUnitProperty($property); | |
} | |
private function isNotPhpUnitProperty(\ReflectionProperty $property) | |
{ | |
return 0 !== strpos($property->getDeclaringClass()->getName(), self::PHPUNIT_PROPERTY_PREFIX); | |
} | |
private function freeProperty(Test $test, \ReflectionProperty $property) | |
{ | |
$property->setAccessible(true); | |
$property->setValue($test, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment