julienmonnerie/kirby/src/Cms/HasMethods.php

71 lines
1.4 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Cms;
2025-04-21 18:57:21 +02:00
use Closure;
2022-06-17 17:51:59 +02:00
use Kirby\Exception\BadMethodCallException;
/**
* HasMethods
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
trait HasMethods
{
2022-08-31 15:02:43 +02:00
/**
* All registered methods
*/
2025-04-21 18:57:21 +02:00
public static array $methods = [];
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Calls a registered method class with the
* passed arguments
* @internal
2025-04-21 18:57:21 +02:00
*
2022-08-31 15:02:43 +02:00
* @throws \Kirby\Exception\BadMethodCallException
*/
2025-04-21 18:57:21 +02:00
public function callMethod(string $method, array $args = []): mixed
2022-08-31 15:02:43 +02:00
{
$closure = $this->getMethod($method);
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
if ($closure === null) {
throw new BadMethodCallException('The method ' . $method . ' does not exist');
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return $closure->call($this, ...$args);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Checks if the object has a registered method
* @internal
*/
public function hasMethod(string $method): bool
{
return $this->getMethod($method) !== null;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns a registered method by name, either from
* the current class or from a parent class ordered by
* inheritance order (top to bottom)
*/
2025-04-21 18:57:21 +02:00
protected function getMethod(string $method): Closure|null
2022-08-31 15:02:43 +02:00
{
if (isset(static::$methods[$method]) === true) {
return static::$methods[$method];
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
foreach (class_parents($this) as $parent) {
if (isset($parent::$methods[$method]) === true) {
return $parent::$methods[$method];
}
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
return null;
}
2022-06-17 17:51:59 +02:00
}