Skip to content

Instantly share code, notes, and snippets.

@yitznewton
Created July 8, 2022 04:10
Show Gist options
  • Save yitznewton/f23771367ec037631f2983ec98b9bb64 to your computer and use it in GitHub Desktop.
Save yitznewton/f23771367ec037631f2983ec98b9bb64 to your computer and use it in GitHub Desktop.
Stub for fluent interface
<?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