Skip to content

Commit a177963

Browse files
committed
New function allowing to call private method on object
1 parent 0408b6c commit a177963

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/Spamer/DependencyMocker/Mocker.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,22 @@ public static function getProperty($class, $property, $object)
133133
$property->setAccessible(TRUE);
134134
return $property->getValue($object);
135135
}
136+
137+
138+
/**
139+
* Calls private method and returns result.
140+
*
141+
* @param object $object
142+
* @param string $method
143+
* @param array $arguments
144+
* @return mixed
145+
*/
146+
public static function callPrivateFunction($object, $method, $arguments = [])
147+
{
148+
$reflectionClass = new \ReflectionClass($object);
149+
$reflectionMethod = $reflectionClass->getMethod($method);
150+
$reflectionMethod->setAccessible(TRUE);
151+
152+
return $reflectionMethod->invokeArgs($object, $arguments);
153+
}
136154
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
require_once __DIR__ . '/../../bootstrap.php';
4+
5+
class TestClass
6+
{
7+
private function saltPassword($string)
8+
{
9+
return $string . 'salt';
10+
}
11+
}
12+
13+
14+
15+
class TestCallPrivateFunction extends \Tester\TestCase
16+
{
17+
public function testCall()
18+
{
19+
$testClass = new TestClass();
20+
21+
$result = \Spamer\DependencyMocker\Mocker::callPrivateFunction($testClass, 'saltPassword', ['string']);
22+
23+
\Tester\Assert::same('stringsalt', $result);
24+
}
25+
26+
}
27+
(new TestCallPrivateFunction())->run();

tests/bootstrap.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
if (@ ! include __DIR__ . '/../vendor/autoload.php') {
4+
echo 'Install Nette Tester using `composer update --dev`';
5+
exit(1);
6+
}
7+
8+
\Tester\Environment::setup();

0 commit comments

Comments
 (0)