Snippets

BelkaLab Frequent actions used in PHPUnit tests

Created by matteo83 last modified
<?php
namespace Blk\Em2\Container\Update;

use ReflectionClass;

/**
 * Class PHPUnitUtils
 * @package Blk\Em2\Container\Update
 * @author Belka.us
 */
class PHPUnitUtils
{
    /**
     * Get a private or protected method for testing/documentation purposes.
     *
     * Ex:
     * getting MyClass::foo():
     *      $cls = new MyClass();
     *      $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
     *      $foo->invoke($cls, $...);
     *
     * @param object $obj The instance of your class
     * @param string $name The name of your private/protected method
     * @param bool $fallbackParent method lookup up thru the parent hierarchy
     * 
     * @return ReflectionMethod | false The method you asked for, false if not found
     */
    public static function getPrivateMethod($obj, $name, $fallbackParent = false) :\ReflectionMethod
    {
        $rc = new ReflectionClass($obj);

        if(!$rc->hasMethod($name) && $fallbackParent) {
            while($rc = $rc->getParentClass()) {
                if($rc->hasMethod($name))
                    break;
            }
        }

        if(!$rc->hasMethod($name))
            return false;

        $method = $rc->getMethod($name);
        $method->setAccessible(true);
        return $method;
    }

    public static function getPrivateAttribute($obj, $name, $fallbackParent = false)
    {
        $rc = new ReflectionClass($obj);

        if(!$rc->hasProperty($name) && $fallbackParent) {
            while($rc = $rc->getParentClass()) {
                if($rc->hasProperty($name))
                    break;
            }
        }

        if(!$rc->hasProperty($name))
            return false;

        $reflectedProperty = $rc->getProperty($name);
        $reflectedProperty->setAccessible(true);
        return $reflectedProperty->getValue($obj);
    }

    public static function setPrivateAttribute($obj, $name, $value, $fallbackParent = false)
    {
        $rc = new \ReflectionClass($obj);

        if(!$rc->hasProperty($name) && $fallbackParent) {
            while($rc = $rc->getParentClass()) {
                if($rc->hasProperty($name))
                    break;
            }
        }

        if(!$rc->hasProperty($name))
            return false;

        $prop = $rc->getProperty($name);
        $prop->setAccessible(true);
        $prop->setValue($obj, $value);
    }
}
?>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.