Created
September 25, 2020 09:50
-
-
Save wonzbak/aed1e07c52091a26ee78cb2baf780126 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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