ajax_wrapper-1.0.1/src/Utility/AjaxWrapperCallbackUtility.php
src/Utility/AjaxWrapperCallbackUtility.php
<?php
namespace Drupal\ajax_wrapper\Utility;
use Drupal\Core\Controller\ControllerResolverInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Security\DoTrustedCallbackTrait;
/**
* Helps us with returning callbacks for the ajax_wrapper.
*
* @package Drupal\ajax_wrapper\Utility
*/
class AjaxWrapperCallbackUtility {
use DoTrustedCallbackTrait;
/**
* The controller resolver.
*
* @var \Drupal\Core\Controller\ControllerResolverInterface
*/
private ControllerResolverInterface $controllerResolver;
/**
* Resolves classes.
*
* @var \Drupal\Core\DependencyInjection\ClassResolverInterface
*/
private ClassResolverInterface $classResolver;
/**
* AjaxWrapperCallbackUtility constructor.
*
* @param \Drupal\Core\Controller\ControllerResolverInterface $controllerResolver
* The controller resolver.
* @param \Drupal\Core\DependencyInjection\ClassResolverInterface $classResolver
* Helps us with resolving classes.
*/
public function __construct(ControllerResolverInterface $controllerResolver, ClassResolverInterface $classResolver) {
$this->controllerResolver = $controllerResolver;
$this->classResolver = $classResolver;
}
/**
* Does the callback.
*
* @param mixed $callback
* The callback.
* @param mixed $arguments
* The arguments.
* @param string $message
* The message when failing.
*
* @return mixed
* The callback value.
*/
public function doCallback($callback, $arguments, $message = 'Callback is not formed correctly') {
if (is_callable($callback)) {
return $this->doTrustedCallback($callback, $arguments, $message);
}
if (is_string($callback)) {
$double_colon = strpos($callback, '::');
if ($double_colon === FALSE) {
$callback = $this->controllerResolver->getControllerFromDefinition($callback);
}
elseif ($double_colon > 0) {
$callback = explode('::', $callback, 2);
}
}
if (is_array($callback[0]) && !empty($callback[0]['_serviceId'])) {
$class = $this->classResolver->getInstanceFromDefinition($callback[0]['_serviceId']);
$callback[0] = $class;
}
if (!is_callable($callback)) {
throw new \Error('Could not create a callable callback to refresh the ajax wrapper!');
}
return $this->doTrustedCallback($callback, $arguments, $message);
}
}
