* * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Scc\PhpUnit\Traits; /** * Trait ReflectionTrait. * * Provide useful method to get and set protected and private properties and methods */ trait ReflectionUnitTests { /** * Get a method by reflection. * * @param string $method * * @throws \ReflectionException */ public function getReflectedMethod($object, $method): \ReflectionMethod { $reflectedInstance = new \ReflectionClass($object); $reflectedMethod = $reflectedInstance->getMethod($method); $reflectedMethod->setAccessible(true); return $reflectedMethod; } /** * @param $instance * @param $expected * @param string $type * * @throws \ReflectionException */ public function checkProperty($instance, $expected, string $name, string $getter, string $setter, string $type = null): void { if ('float' === $type) { self::setProperty($instance, $name, (float) $expected); $this->assertEqualsWithDelta($expected, $instance->{$getter}(), 0.0001); $this->assertEqualsWithDelta($instance, $instance->{$setter}($expected), 0.0001); $this->assertEqualsWithDelta($expected, self::getProperty($instance, $name), 0.0001); } else { self::setProperty($instance, $name, $expected); $this->assertSame($expected, $instance->{$getter}()); $this->assertSame($instance, $instance->{$setter}($expected)); $this->assertSame($expected, self::getProperty($instance, $name)); } } /** * Set a property by reflection. * * @throws \ReflectionException if the class does not exist */ protected static function setProperty($object, string $name, $value): \ReflectionProperty { $class = new \ReflectionClass($object); $property = $class->getProperty($name); $property->setAccessible(true); $property->setValue($object, $value); return $property; } /** * Get a property by reflection. * * @throws \ReflectionException if the class does not exist */ protected static function getProperty($object, string $name) { $class = new \ReflectionClass($object); $property = $class->getProperty($name); $property->setAccessible(true); return $property->getValue($object); } /** * Return the classes which implements the given class name. * * @param string $classname * * @throws \ReflectionException if the class does not exist */ protected function getInstanceOfTypes($classname): array { $classes = get_declared_classes(); $transformations = []; foreach ($classes as $class) { $reflect = new \ReflectionClass($class); if ($reflect->implementsInterface($classname) && !$reflect->isAbstract()) { if (false !== strpos($class, 'Mock')) { continue; } $transformations[] = $class; } } return $transformations; } }