ScriptPlacementManager.php in Script Manager 8
File
src/ScriptPlacementManager.php
View source
<?php
namespace Drupal\script_manager;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ScriptPlacementManager implements ContainerInjectionInterface {
protected $scriptStorage;
protected $isAdminRoute;
protected $moduleHandler;
public function __construct(EntityStorageInterface $scriptStorage, $isAdminRoute, ModuleHandlerInterface $moduleHandler) {
$this->scriptStorage = $scriptStorage;
$this->isAdminRoute = $isAdminRoute;
$this->moduleHandler = $moduleHandler;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager')
->getStorage('script'), $container
->get('router.admin_context')
->isAdminRoute(), $container
->get('module_handler'));
}
public function getRenderedScriptsForPosition($position) {
if ($this->isAdminRoute) {
return [];
}
$scripts = $this->scriptStorage
->loadByProperties([
'position' => $position,
]);
$rendered_scripts = [
'#cache' => [
'tags' => [
'config:script_list',
],
],
];
foreach ($scripts as $script) {
$access = $script
->access('view', NULL, TRUE);
$rendered = [
'#markup' => new FormattableMarkup($script
->getSnippet(), []),
'#access' => $access
->isAllowed(),
];
CacheableMetadata::createFromObject($access)
->addCacheableDependency($script)
->applyTo($rendered);
$rendered_scripts[] = $rendered;
}
$this->moduleHandler
->alter('script_manager_scripts', $rendered_scripts);
return $rendered_scripts;
}
}