julienmonnerie/kirby/src/Toolkit/Controller.php

68 lines
1.2 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Toolkit;
use Closure;
use Kirby\Filesystem\F;
use ReflectionFunction;
/**
* A smart extension of Closures with
* magic dependency injection based on the
* defined variable names.
*
* @package Kirby Toolkit
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Controller
{
2022-08-31 15:02:43 +02:00
protected $function;
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
public function __construct(Closure $function)
{
$this->function = $function;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
public function arguments(array $data = []): array
{
$info = new ReflectionFunction($this->function);
$args = [];
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
foreach ($info->getParameters() as $parameter) {
$name = $parameter->getName();
$args[] = $data[$name] ?? null;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return $args;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
public function call($bind = null, $data = [])
{
$args = $this->arguments($data);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if ($bind === null) {
return call_user_func($this->function, ...$args);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return $this->function->call($bind, ...$args);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
public static function load(string $file)
{
if (is_file($file) === false) {
return null;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
$function = F::load($file);
2022-06-17 17:51:59 +02:00
2022-12-19 14:56:05 +01:00
if ($function instanceof Closure === false) {
2022-08-31 15:02:43 +02:00
return null;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return new static($function);
}
2022-06-17 17:51:59 +02:00
}