Skip to content

Commit

Permalink
New function allowing to call private method on object
Browse files Browse the repository at this point in the history
  • Loading branch information
Spamercz committed Feb 8, 2016
1 parent 0408b6c commit a177963
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Spamer/DependencyMocker/Mocker.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,22 @@ public static function getProperty($class, $property, $object)
$property->setAccessible(TRUE);
return $property->getValue($object);
}


/**
* Calls private method and returns result.
*
* @param object $object
* @param string $method
* @param array $arguments
* @return mixed
*/
public static function callPrivateFunction($object, $method, $arguments = [])
{
$reflectionClass = new \ReflectionClass($object);
$reflectionMethod = $reflectionClass->getMethod($method);
$reflectionMethod->setAccessible(TRUE);

return $reflectionMethod->invokeArgs($object, $arguments);
}
}
27 changes: 27 additions & 0 deletions tests/DependencyMocker/Mocker/CallPrivateFunction.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

require_once __DIR__ . '/../../bootstrap.php';

class TestClass
{
private function saltPassword($string)
{
return $string . 'salt';
}
}



class TestCallPrivateFunction extends \Tester\TestCase
{
public function testCall()
{
$testClass = new TestClass();

$result = \Spamer\DependencyMocker\Mocker::callPrivateFunction($testClass, 'saltPassword', ['string']);

\Tester\Assert::same('stringsalt', $result);
}

}
(new TestCallPrivateFunction())->run();
8 changes: 8 additions & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

if (@ ! include __DIR__ . '/../vendor/autoload.php') {
echo 'Install Nette Tester using `composer update --dev`';
exit(1);
}

\Tester\Environment::setup();

0 comments on commit a177963

Please sign in to comment.