1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
<?php
namespace phpmock\generator;
use phpmock\Mock;
use phpmock\MockRegistry;
use SebastianBergmann\Template\Template;
/**
* Generates the mock function.
*
* @author Markus Malkusch <markus@malkusch.de>
* @link bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK Donations
* @license http://www.wtfpl.net/txt/copying/ WTFPL
* @internal
*/
class MockFunctionGenerator
{
/**
* @var string The internal name for optional parameters.
*/
const DEFAULT_ARGUMENT = "optionalParameter";
/**
* @var Mock The mock.
*/
private $mock;
/**
* @var Template The function template.
*/
private $template;
/**
* Sets the mock.
*
* @param Mock $mock The mock.
*/
public function __construct(Mock $mock)
{
$this->mock = $mock;
$this->template = new Template(__DIR__ . '/function.tpl');
}
/**
* Defines the mock function.
*
* @SuppressWarnings(PHPMD)
*/
public function defineFunction()
{
$name = $this->mock->getName();
$parameterBuilder = new ParameterBuilder();
$parameterBuilder->build($name);
$data = [
"namespace" => $this->mock->getNamespace(),
"name" => $name,
"fqfn" => $this->mock->getFQFN(),
"signatureParameters" => $parameterBuilder->getSignatureParameters(),
"bodyParameters" => $parameterBuilder->getBodyParameters(),
];
$this->template->setVar($data, false);
$definition = $this->template->render();
eval($definition);
}
/**
* Removes optional arguments.
*
* @param array $arguments The arguments.
*/
public static function removeDefaultArguments(&$arguments)
{
foreach ($arguments as $key => $argument) {
if ($argument === self::DEFAULT_ARGUMENT) {
unset($arguments[$key]);
}
}
}
/**
* Calls the enabled mock, or the built-in function otherwise.
*
* @param string $functionName The function name.
* @param string $fqfn The fully qualified function name.
* @param array $arguments The arguments.
*
* @return mixed The result of the called function.
* @see Mock::define()
* @SuppressWarnings(PHPMD)
*/
public static function call($functionName, $fqfn, &$arguments)
{
$registry = MockRegistry::getInstance();
$mock = $registry->getMock($fqfn);
self::removeDefaultArguments($arguments);
if (empty($mock)) {
// call the built-in function if the mock was not enabled.
return call_user_func_array($functionName, $arguments);
} else {
// call the mock function.
return $mock->call($arguments);
}
}
}
|