Skip to content

Instantly share code, notes, and snippets.

@bayareawebpro
Last active March 29, 2022 06:09
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 bayareawebpro/6c4835daa23e7193744662a3d3b1de13 to your computer and use it in GitHub Desktop.
Save bayareawebpro/6c4835daa23e7193744662a3d3b1de13 to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Support\Collection;
/**
* @method self registerCustomer(Closure $query, Closure $filter)
* @method self registerAccounts(Closure $query, Closure $filter)
*/
class Manager
{
// Allowed virtual methods.
private array $methods = [
'customer',
'accounts'
];
private Collection $callbacks;
public function __construct()
{
$this->callbacks = new Collection;
}
public function __call($method, $args)
{
$type = (string)str($method)->remove('register')->lower();
//Allow virtual public methods to be called.
if (!in_array($type, $this->methods)) {
throw new BadMethodCallException();
}
$this->callVirtualMethod($type, $args);
return $this;
}
protected function callVirtualMethod($type, $args): void
{
$this->callbacks->put($type, [
$type => [
'query' => $args[0],
'filter' => $args[1],
]
]);
}
public function getCallbacks(string $type): stdClass
{
if(!$this->callbacks->has($type)){
throw new InvalidArgumentException(
'Required callback must be registered: '. (string)str($type)->title()->prepend('register'))
);
}
return (object) $this->callbacks->get($type);
}
}
@bayareawebpro
Copy link
Author

bayareawebpro commented Mar 29, 2022

dd((new Manager)->registerCustomer(fn()=>true, fn()=>false)->getCallbacks('customer'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment