Skip to content

Commit

Permalink
add executeCallback in DcaUtil to replace v2's getConfigByArrayOrCall…
Browse files Browse the repository at this point in the history
…backOrFunction
  • Loading branch information
ericges committed Mar 12, 2024
1 parent 9445ecb commit 3877878
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Util/DcaUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use Contao\CoreBundle\DataContainer\PaletteNotFoundException;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\StringUtil;
use Error;
use Exception;
use HeimrichHannot\UtilsBundle\Util\DcaUtil\GetDcaFieldsOptions;

class DcaUtil
Expand Down Expand Up @@ -186,4 +188,53 @@ public function getDcaFields(string $table, GetDcaFieldsOptions $options = new G

return $fields;
}

/**
* Execute a callback with given arguments.
*
* @param array|callable|null $callback The callback can be a callable or an array with the first element being
* the class name and the second element being the method name.
*
* @return mixed|null The retrieved value or null if the callback is not callable or an error occurred.
*/
public function executeCallback(array|callable|null $callback, mixed ...$arguments): mixed
{
if (!$callback) {
return null;
}

if (is_array($callback))
{
if (!isset($callback[0]) || !isset($callback[1])) {
return null;
}

try {
/** @var Controller $controller */
$controller = $this->contaoFramework->getAdapter(Controller::class);
$instance = $controller->importStatic($callback[0]);
} catch (Exception) {
return null;
}

if (!method_exists($instance, $callback[1])) {
return null;
}

$callback = [$instance, $callback[1]];
}
elseif (!is_callable($callback))
{
return null;
}

try
{
return call_user_func_array($callback, $arguments);
}
catch (Error)
{
return null;
}
}
}

0 comments on commit 3877878

Please sign in to comment.