merge main -> preprod

This commit is contained in:
isUnknown 2025-10-05 17:31:53 +02:00
commit 33ec908a23
35 changed files with 3443 additions and 3265 deletions

View file

@ -2,46 +2,27 @@
namespace Kirby\Kql;
use Kirby\Toolkit\A;
use ReflectionClass;
use ReflectionMethod;
/**
* Providing help information about
* queried objects, methods, arrays...
*
* @package Kirby KQL
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Help
{
/**
* Provides information about passed value
* depending on its type
*/
public static function for($value): array
public static function for($object)
{
if (is_array($value) === true) {
return static::forArray($value);
if (is_array($object) === true) {
return static::forArray($object);
}
if (is_object($value) === true) {
return static::forObject($value);
if (is_object($object) === true) {
return static::forObject($object);
}
return [
'type' => gettype($value),
'value' => $value
'type' => gettype($object),
'value' => $object
];
}
/**
* @internal
*/
public static function forArray(array $array): array
public static function forArray(array $array)
{
return [
'type' => 'array',
@ -49,42 +30,42 @@ class Help
];
}
/**
* Gathers information for method about
* name, parameters, return type etc.
* @internal
*/
public static function forMethod(object $object, string $method): array
public static function forMethod($object, $method)
{
$reflection = new ReflectionMethod($object, $method);
$returns = $reflection->getReturnType()?->getName();
$returns = null;
$params = [];
if ($returnType = $reflection->getReturnType()) {
$returns = $returnType->getName();
}
foreach ($reflection->getParameters() as $param) {
$name = $param->getName();
$required = $param->isOptional() === false;
$type = $param->hasType() ? $param->getType()->getName() : null;
$default = null;
$p = [
'name' => $param->getName(),
'required' => $param->isOptional() === false,
'type' => $param->hasType() ? $param->getType()->getName() : null,
];
if ($param->isDefaultValueAvailable()) {
$default = $param->getDefaultValue();
$p['default'] = $param->getDefaultValue();
}
$call = '';
$call = null;
if ($type !== null) {
$call = $type . ' ';
if ($p['type'] !== null) {
$call = $p['type'] . ' ';
}
$call .= '$' . $name;
$call .= '$' . $p['name'];
if ($required === false && $default !== null) {
$call .= ' = ' . var_export($default, true);
if ($p['required'] === false && isset($p['default']) === true) {
$call .= ' = ' . var_export($p['default'], true);
}
$p['call'] = $call;
$params[$name] = compact('name', 'type', 'required', 'default', 'call');
$params[$p['name']] = $p;
}
$call = '.' . $method;
@ -101,11 +82,7 @@ class Help
];
}
/**
* Gathers informations for each unique method
* @internal
*/
public static function forMethods(object $object, array $methods): array
public static function forMethods($object, $methods)
{
$methods = array_unique($methods);
$reflection = [];
@ -123,30 +100,11 @@ class Help
return $reflection;
}
/**
* Retrieves info for objects either from Interceptor (to
* only list allowed methods) or via reflection
* @internal
*/
public static function forObject(object $object): array
public static function forObject($object)
{
// get interceptor object to only return info on allowed methods
$interceptor = Interceptor::replace($object);
$original = $object;
$object = Interceptor::replace($original);
if ($interceptor instanceof Interceptor) {
return $interceptor->__debugInfo();
}
// for original classes, use reflection
$class = new ReflectionClass($object);
$methods = A::map(
$class->getMethods(),
fn ($method) => static::forMethod($object, $method->getName())
);
return [
'type' => $class->getName(),
'methods' => $methods
];
return $object->__debugInfo();
}
}

View file

@ -2,294 +2,58 @@
namespace Kirby\Kql;
use Closure;
use Kirby\Cms\App;
use Kirby\Exception\InvalidArgumentException;
use Exception;
use Kirby\Exception\PermissionException;
use Kirby\Toolkit\Str;
use ReflectionFunction;
use ReflectionMethod;
use Throwable;
/**
* Base class for proxying core classes to
* intercept method calls that are not allowed
* on the related core class
*
* @package Kirby KQL
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
abstract class Interceptor
class Interceptor
{
public const CLASS_ALIAS = null;
protected $toArray = [];
public function __construct(protected $object)
{
}
/**
* Magic caller that prevents access
* to restricted methods
*/
public function __call(string $method, array $args = [])
{
if ($this->isAllowedMethod($method) === true) {
return $this->object->$method(...$args);
}
$this->forbiddenMethod($method);
}
/**
* Return information about corresponding object
* incl. information about allowed methods
*/
public function __debugInfo(): array
{
$help = Help::forMethods($this->object, $this->allowedMethods());
return [
'type' => $this::CLASS_ALIAS,
'methods' => $help,
'value' => $this->toArray()
];
}
/**
* Returns list of allowed classes. Specific list
* to be implemented in specific interceptor child classes.
* @codeCoverageIgnore
*/
public function allowedMethods(): array
{
return [];
}
/**
* Returns class name for Interceptor that responds
* to passed name string of a Kirby core class
* @internal
*/
public static function class(string $class): string
{
return str_replace('Kirby\\', 'Kirby\\Kql\\Interceptors\\', $class);
}
/**
* Throws exception for accessing a restricted method
* @throws \Kirby\Exception\PermissionException
*/
protected function forbiddenMethod(string $method)
{
$name = get_class($this->object) . '::' . $method . '()';
throw new PermissionException('The method "' . $name . '" is not allowed in the API context');
}
/**
* Checks if method is allowed to call
*/
public function isAllowedMethod($method)
{
$kirby = App::instance();
$name = strtolower(get_class($this->object) . '::' . $method);
// get list of blocked methods from config
$blocked = $kirby->option('kql.methods.blocked', []);
$blocked = array_map('strtolower', $blocked);
// check in the block list from the config
if (in_array($name, $blocked) === true) {
return false;
}
// check in class allow list
if (in_array($method, $this->allowedMethods()) === true) {
return true;
}
// get list of explicitly allowed methods from config
$allowed = $kirby->option('kql.methods.allowed', []);
$allowed = array_map('strtolower', $allowed);
// check in the allow list from the config
if (in_array($name, $allowed) === true) {
return true;
}
// support for model methods with docblock comment
if ($this->isAllowedCallable($method) === true) {
return true;
}
// support for custom methods with docblock comment
if ($this->isAllowedCustomMethod($method) === true) {
return true;
}
return false;
}
/**
* Checks if closure or object method is allowed
*/
protected function isAllowedCallable($method): bool
{
try {
$ref = match (true) {
$method instanceof Closure
=> new ReflectionFunction($method),
is_string($method) === true
=> new ReflectionMethod($this->object, $method),
default
=> throw new InvalidArgumentException('Invalid method')
};
if ($comment = $ref->getDocComment()) {
if (Str::contains($comment, '@kql-allowed') === true) {
return true;
}
}
} catch (Throwable) {
return false;
}
return false;
}
protected function isAllowedCustomMethod(string $method): bool
{
// has no custom methods
if (property_exists($this->object, 'methods') === false) {
return false;
}
// does not have that method
if (!$call = $this->method($method)) {
return false;
}
// check for a docblock comment
if ($this->isAllowedCallable($call) === true) {
return true;
}
return false;
}
/**
* Returns a registered method by name, either from
* the current class or from a parent class ordered by
* inheritance order (top to bottom)
*/
protected function method(string $method)
{
if (isset($this->object::$methods[$method]) === true) {
return $this->object::$methods[$method];
}
foreach (class_parents($this->object) as $parent) {
if (isset($parent::$methods[$method]) === true) {
return $parent::$methods[$method];
}
}
return null;
}
/**
* Tries to replace a Kirby core object with the
* corresponding interceptor.
* @throws \Kirby\Exception\InvalidArgumentException for non-objects
* @throws \Kirby\Exception\PermissionException when accessing blocked class
*/
public static function replace($object)
{
if (is_object($object) === false) {
throw new InvalidArgumentException('Unsupported value: ' . gettype($object));
throw new Exception('Unsupported value: ' . gettype($object));
}
$kirby = App::instance();
$class = get_class($object);
$name = strtolower($class);
// 1. Is $object class explicitly blocked?
// get list of blocked classes from config
$blocked = $kirby->option('kql.classes.blocked', []);
$blocked = array_map('strtolower', $blocked);
$className = get_class($object);
$fullName = strtolower($className);
$blocked = array_map('strtolower', option('kql.classes.blocked', []));
// check in the block list from the config
if (in_array($name, $blocked) === true) {
throw new PermissionException('Access to the class "' . $class . '" is blocked');
if (in_array($fullName, $blocked) === true) {
throw new PermissionException('Access to the class "' . $className . '" is blocked');
}
// 2. Is $object already an interceptor?
// directly return interceptor objects
if ($object instanceof Interceptor) {
if (is_a($object, 'Kirby\\Kql\\Interceptors\\Interceptor') === true) {
return $object;
}
// 3. Does an interceptor class for $object exist?
// check for an interceptor class
$interceptors = $kirby->option('kql.interceptors', []);
$interceptors = array_change_key_case($interceptors, CASE_LOWER);
$interceptors = array_change_key_case(option('kql.interceptors', []), CASE_LOWER);
// load an interceptor from config if it exists and otherwise fall back to a built-in interceptor
$interceptor = $interceptors[$name] ?? static::class($class);
$interceptor = $interceptors[$fullName] ?? str_replace('Kirby\\', 'Kirby\\Kql\\Interceptors\\', $className);
// check for a valid interceptor class
if ($class !== $interceptor && class_exists($interceptor) === true) {
if ($className !== $interceptor && class_exists($interceptor) === true) {
return new $interceptor($object);
}
// 4. Also check for parent classes of $object
// go through parents of the current object to use their interceptors as fallback
foreach (class_parents($object) as $parent) {
$interceptor = static::class($parent);
$interceptor = str_replace('Kirby\\', 'Kirby\\Kql\\Interceptors\\', $parent);
if (class_exists($interceptor) === true) {
return new $interceptor($object);
}
}
// 5. $object has no interceptor but is explicitly allowed?
// check for a class in the allow list
$allowed = $kirby->option('kql.classes.allowed', []);
$allowed = array_map('strtolower', $allowed);
$allowed = array_map('strtolower', option('kql.classes.allowed', []));
// return the plain object if it is allowed
if (in_array($name, $allowed) === true) {
if (in_array($fullName, $allowed) === true) {
return $object;
}
// 6. None of the above? Block class.
throw new PermissionException('Access to the class "' . $class . '" is not supported');
}
public function toArray(): array|null
{
$toArray = [];
// filter methods which cannot be called
foreach ($this->toArray as $method) {
if ($this->isAllowedMethod($method) === true) {
$toArray[] = $method;
}
}
return Kql::select($this, $toArray);
}
/**
* Mirrors by default ::toArray but can be
* implemented differently by specifc interceptor.
* KQL will prefer ::toResponse over ::toArray
*/
public function toResponse()
{
return $this->toArray();
throw new PermissionException('Access to the class "' . $className . '" is not supported');
}
}

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class App extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Blueprint extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Collection extends Interceptor
{

View file

@ -1,8 +1,8 @@
<?php
namespace Kirby\Kql\Interceptors\Content;
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Content extends Interceptor
{

View file

@ -1,8 +1,8 @@
<?php
namespace Kirby\Kql\Interceptors\Content;
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Field extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Model extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Role extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Cms;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Translation extends Interceptor
{

View file

@ -0,0 +1,174 @@
<?php
namespace Kirby\Kql\Interceptors;
use Exception;
use Kirby\Exception\PermissionException;
use Kirby\Kql\Help;
use Kirby\Kql\Kql;
use Kirby\Toolkit\Str;
use ReflectionFunction;
use ReflectionMethod;
use Throwable;
abstract class Interceptor
{
public const CLASS_ALIAS = null;
protected $object;
protected $toArray = [];
public function __construct($object)
{
$this->object = $object;
}
public function __call($method, array $args = [])
{
if ($this->isAllowedMethod($method) === true) {
return $this->object->$method(...$args);
}
$this->forbiddenMethod($method);
}
public function allowedMethods(): array
{
return [];
}
protected function forbiddenMethod(string $method)
{
$className = get_class($this->object);
throw new PermissionException('The method "' . $className . '::' . $method . '()" is not allowed in the API context');
}
/**
* Returns a registered method by name, either from
* the current class or from a parent class ordered by
* inheritance order (top to bottom)
*
* @param string $method
* @return \Closure|null
*/
protected function getMethod(string $method)
{
if (isset($this->object::$methods[$method]) === true) {
return $this->object::$methods[$method];
}
foreach (class_parents($this->object) as $parent) {
if (isset($parent::$methods[$method]) === true) {
return $parent::$methods[$method];
}
}
return null;
}
protected function isAllowedCallable($method): bool
{
try {
if (is_a($method, 'Closure') === true) {
$ref = new ReflectionFunction($method);
} elseif (is_string($method) === true) {
$ref = new ReflectionMethod($this->object, $method);
} else {
throw new Exception('Invalid method');
}
if ($comment = $ref->getDocComment()) {
if (Str::contains($comment, '@kql-allowed') === true) {
return true;
}
}
} catch (Throwable $e) {
return false;
}
return false;
}
protected function isAllowedMethod($method)
{
$fullName = strtolower(get_class($this->object) . '::' . $method);
$blocked = array_map('strtolower', option('kql.methods.blocked', []));
// check in the block list from the config
if (in_array($fullName, $blocked) === true) {
return false;
}
// check in class allow list
if (in_array($method, $this->allowedMethods()) === true) {
return true;
}
$allowed = array_map('strtolower', option('kql.methods.allowed', []));
// check in the allow list from the config
if (in_array($fullName, $allowed) === true) {
return true;
}
// support for model methods with docblock comment
if ($this->isAllowedCallable($method) === true) {
return true;
}
// support for custom methods with docblock comment
if ($this->isAllowedCustomMethod($method) === true) {
return true;
}
return false;
}
protected function isAllowedCustomMethod(string $method): bool
{
// has no custom methods
if (property_exists($this->object, 'methods') === false) {
return false;
}
// does not have that method
if (!$call = $this->getMethod($method)) {
return false;
}
// check for a docblock comment
if ($this->isAllowedCallable($call) === true) {
return true;
}
return false;
}
public function __debugInfo(): array
{
return [
'type' => $this::CLASS_ALIAS,
'methods' => Help::forMethods($this->object, $this->allowedMethods()),
'value' => $this->toArray()
];
}
public function toArray(): ?array
{
$toArray = [];
// filter methods which cannot be called
foreach ($this->toArray as $method) {
if ($this->isAllowedMethod($method) === true) {
$toArray[] = $method;
}
}
return Kql::select($this, $toArray);
}
public function toResponse()
{
return $this->toArray();
}
}

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Panel;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Model extends Interceptor
{

View file

@ -2,7 +2,7 @@
namespace Kirby\Kql\Interceptors\Toolkit;
use Kirby\Kql\Interceptor;
use Kirby\Kql\Interceptors\Interceptor;
class Obj extends Interceptor
{

View file

@ -3,81 +3,16 @@
namespace Kirby\Kql;
use Exception;
use Kirby\Cms\App;
use Kirby\Cms\Collection;
use Kirby\Toolkit\Str;
/**
* ...
*
* @package Kirby KQL
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Kql
{
public static function fetch($model, $key, $selection)
{
// simple key/value
if ($selection === true) {
return static::render($model->$key());
}
// selection without additional query
if (
is_array($selection) === true &&
empty($selection['query']) === true
) {
return static::select(
$model->$key(),
$selection['select'] ?? null,
$selection['options'] ?? []
);
}
// nested queries
return static::run($selection, $model);
}
/**
* Returns helpful information about the object
* type as well as, if available, values and methods
*/
public static function help($object): array
public static function help($object)
{
return Help::for($object);
}
public static function query(string $query, $model = null)
{
$model ??= App::instance()->site();
$data = [$model::CLASS_ALIAS => $model];
return Query::factory($query)->resolve($data);
}
public static function render($value)
{
if (is_object($value) === true) {
// replace actual object with intercepting proxy class
$object = Interceptor::replace($value);
if (method_exists($object, 'toResponse') === true) {
return $object->toResponse();
}
if (method_exists($object, 'toArray') === true) {
return $object->toArray();
}
throw new Exception('The object "' . get_class($object) . '" cannot be rendered. Try querying one of its methods instead.');
}
return $value;
}
public static function run($input, $model = null)
{
// string queries
@ -97,9 +32,11 @@ class Kql
return $result;
}
$query = $input['query'] ?? 'site';
$query = $input['query'] ?? 'site';
$select = $input['select'] ?? null;
$options = ['pagination' => $input['pagination'] ?? null];
$options = [
'pagination' => $input['pagination'] ?? null,
];
// check for invalid queries
if (is_string($query) === false) {
@ -107,14 +44,74 @@ class Kql
}
$result = static::query($query, $model);
return static::select($result, $select, $options);
}
public static function select(
$data,
array|string|null $select = null,
array $options = []
) {
public static function fetch($model, $key, $selection)
{
// simple key/value
if ($selection === true) {
return static::render($model->$key());
}
// selection without additional query
if (is_array($selection) === true && empty($selection['query']) === true) {
return static::select($model->$key(), $selection['select'] ?? null, $selection['options'] ?? []);
}
// nested queries
return static::run($selection, $model);
}
public static function query(string $query, $model = null)
{
$kirby = kirby();
$site = $kirby->site();
$model = $model ?? $site;
$query = new Query($query, [
'collection' => function (string $id) use ($kirby) {
return $kirby->collection($id);
},
'file' => function (string $id) use ($kirby) {
return $kirby->file($id);
},
'kirby' => $kirby,
'page' => function (string $id) use ($site) {
return $site->find($id);
},
'site' => $site,
'user' => function (string $id = null) use ($kirby) {
return $kirby->user($id);
},
$model::CLASS_ALIAS => $model
]);
return $query->result();
}
public static function render($value)
{
if (is_object($value) === true) {
$object = Interceptor::replace($value);
if (method_exists($object, 'toResponse') === true) {
return $object->toResponse();
}
if (method_exists($object, 'toArray') === true) {
return $object->toArray();
}
throw new Exception('The object "' . get_class($object) . '" cannot be rendered. Try querying one of its methods instead.');
}
return $value;
}
public static function select($data, $select, array $options = [])
{
if ($select === null) {
return static::render($data);
}
@ -123,23 +120,20 @@ class Kql
return static::help($data);
}
if ($data instanceof Collection) {
if (is_a($data, 'Kirby\Cms\Collection') === true) {
return static::selectFromCollection($data, $select, $options);
}
if (is_object($data) === true) {
return static::selectFromObject($data, $select);
return static::selectFromObject($data, $select, $options);
}
if (is_array($data) === true) {
return static::selectFromArray($data, $select);
return static::selectFromArray($data, $select, $options);
}
}
/**
* @internal
*/
public static function selectFromArray(array $array, array $select): array
public static function selectFromArray($array, $select, array $options = [])
{
$result = [];
@ -159,14 +153,8 @@ class Kql
return $result;
}
/**
* @internal
*/
public static function selectFromCollection(
Collection $collection,
array|string $select,
array $options = []
): array {
public static function selectFromCollection(Collection $collection, $select, array $options = [])
{
if ($options['pagination'] ?? false) {
$collection = $collection->paginate($options['pagination']);
}
@ -193,14 +181,8 @@ class Kql
return $data;
}
/**
* @internal
*/
public static function selectFromObject(
object $object,
array|string $select
): array {
// replace actual object with intercepting proxy class
public static function selectFromObject($object, $select, array $options = [])
{
$object = Interceptor::replace($object);
$result = [];

View file

@ -2,28 +2,71 @@
namespace Kirby\Kql;
use Kirby\Query\Query as BaseQuery;
use Kirby\Toolkit\Query as BaseQuery;
/**
* Extends the core Query class with the KQL-specific
* functionalities to intercept the segments chain calls
*
* @package Kirby KQL
* @author Nico Hoffmann <nico@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Query extends BaseQuery
{
/**
* Intercepts the chain of segments called
* on each other by replacing objects with
* their corresponding Interceptor which
* handles blocking calls to restricted methods
*/
public function intercept(mixed $result): mixed
protected function interceptor($object)
{
return is_object($result) ? Interceptor::replace($result): $result;
return Interceptor::replace($object);
}
/**
* Resolves the query if anything
* can be found. Otherwise returns null.
*
* @param string $query
* @return mixed
*/
protected function resolve(string $query)
{
// direct key access in arrays
if (is_array($this->data) === true && array_key_exists($query, $this->data) === true) {
$value = $this->data[$query];
// closure resolver
if (is_a($value, 'Closure') === true) {
$value = $value();
}
return $this->interceptor($value);
}
$parts = $this->parts($query);
$data = $this->data;
$value = null;
while (count($parts)) {
$part = array_shift($parts);
$info = $this->part($part);
$method = $info['method'];
$value = null;
if (is_array($data)) {
$value = $data[$method] ?? null;
} elseif (is_object($data)) {
$data = $this->interceptor($data);
if (method_exists($data, $method) || method_exists($data, '__call')) {
$value = $data->$method(...$info['args']);
}
} elseif (is_scalar($data)) {
return $data;
} else {
return null;
}
if (is_a($value, 'Closure') === true) {
$value = $value(...$info['args']);
}
if (is_array($value) === true) {
$data = $value;
} elseif (is_object($value) === true) {
$data = $this->interceptor($value);
}
}
return $value;
}
}