designtopack/public/site/plugins/kql/src/Kql/Interceptor.php

60 lines
1.8 KiB
PHP
Raw Normal View History

2024-07-10 16:10:33 +02:00
<?php
namespace Kirby\Kql;
use Exception;
2024-07-10 16:10:33 +02:00
use Kirby\Exception\PermissionException;
class Interceptor
2024-07-10 16:10:33 +02:00
{
public static function replace($object)
{
if (is_object($object) === false) {
throw new Exception('Unsupported value: ' . gettype($object));
2024-07-10 16:10:33 +02:00
}
$className = get_class($object);
$fullName = strtolower($className);
$blocked = array_map('strtolower', option('kql.classes.blocked', []));
2024-07-10 16:10:33 +02:00
// check in the block list from the config
if (in_array($fullName, $blocked) === true) {
throw new PermissionException('Access to the class "' . $className . '" is blocked');
2024-07-10 16:10:33 +02:00
}
// directly return interceptor objects
if (is_a($object, 'Kirby\\Kql\\Interceptors\\Interceptor') === true) {
2024-07-10 16:10:33 +02:00
return $object;
}
// check for an interceptor class
$interceptors = array_change_key_case(option('kql.interceptors', []), CASE_LOWER);
2024-07-10 16:10:33 +02:00
// load an interceptor from config if it exists and otherwise fall back to a built-in interceptor
$interceptor = $interceptors[$fullName] ?? str_replace('Kirby\\', 'Kirby\\Kql\\Interceptors\\', $className);
2024-07-10 16:10:33 +02:00
// check for a valid interceptor class
if ($className !== $interceptor && class_exists($interceptor) === true) {
2024-07-10 16:10:33 +02:00
return new $interceptor($object);
}
// go through parents of the current object to use their interceptors as fallback
foreach (class_parents($object) as $parent) {
$interceptor = str_replace('Kirby\\', 'Kirby\\Kql\\Interceptors\\', $parent);
2024-07-10 16:10:33 +02:00
if (class_exists($interceptor) === true) {
return new $interceptor($object);
}
}
// check for a class in the allow list
$allowed = array_map('strtolower', option('kql.classes.allowed', []));
2024-07-10 16:10:33 +02:00
// return the plain object if it is allowed
if (in_array($fullName, $allowed) === true) {
2024-07-10 16:10:33 +02:00
return $object;
}
throw new PermissionException('Access to the class "' . $className . '" is not supported');
2024-07-10 16:10:33 +02:00
}
}