Created
July 8, 2022 04:10
-
-
Save yitznewton/f23771367ec037631f2983ec98b9bb64 to your computer and use it in GitHub Desktop.
Stub for fluent interface
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 | |
class Stub | |
{ | |
private array $stubMethods = []; | |
public function stubMethodChain(array $chain, \Closure $callback): void | |
{ | |
if (count($chain) === 0) { | |
return; | |
} | |
if (count($chain) === 1) { | |
$this->stubMethods[$chain[0]] = $callback; | |
return; | |
} | |
$this->stubMethods[$chain[0]] = function () use ($chain, $callback) { | |
$clone = clone $this; | |
$clone->stub(array_slice($chain, 1), $callback); | |
return $clone; | |
}; | |
} | |
public function __call(string $name, array $arguments) | |
{ | |
return $this->stubMethods[$name](); | |
} | |
} | |
$days = ['Monday']; | |
$stub = new Stub(); | |
$stub->stubMethodChain(['days', 'active', 'get', 'load'], fn () => $days); | |
// returns ['Monday'] | |
$stub->days()->active()->get()->load(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment