Skip to content

Instantly share code, notes, and snippets.

@wonzbak
Created September 25, 2020 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonzbak/aed1e07c52091a26ee78cb2baf780126 to your computer and use it in GitHub Desktop.
Save wonzbak/aed1e07c52091a26ee78cb2baf780126 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace Deezer\Legacy\Test\ActivationJourney;
use Prophecy\Prophet;
class MockHelper
{
/** @var Prophet */
private $prophet;
/** @var array */
private $mockDefaultParams;
public function __construct()
{
$this->prophet = new Prophet();
$this->mockDefaultParams = [];
}
public function setDefaultParamsForMock(string $classname, array $defaultParams)
{
$this->mockDefaultParams[$classname] = $defaultParams;
}
public function getMock(string $classname, array $customParams = [])
{
$mockParams = array_merge($this->mockDefaultParams[$classname], $customParams);
$mock = $this->prophet->prophesize($classname);
$reflectionClass = new \ReflectionClass($classname);
foreach ($reflectionClass->getMethods() as $method) {
$methodName = $method->getName();
switch (true) {
case preg_match('/^_/', $methodName):
// magic method
continue(2);
case preg_match('/^(get|is)/', $methodName):
//mock getters
$propertyName = $this->getPropertyNameForAMethod($methodName);
$returnValue = $mockParams[$propertyName] ?? null;
$this->handleGetter($mock, $methodName, $returnValue);
break;
}
}
return $mock->reveal();
}
private function handleGetter($mock, string $methodName, $returnValue): void
{
$mock
->$methodName()
->willReturn($returnValue);
}
private function getPropertyNameForAMethod(string $methodName): string
{
return implode('_', array_slice(explode('_', $this->camelCaseToSnakeCase($methodName)), 1));
}
private function camelCaseToSnakeCase(string $value): string
{
return strtolower(preg_replace('/(.)(?=[A-Z])/', "$1" . '_', $value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment