acquia_vwo-1.0.x-dev/modules/acquia_vwo_content/src/Service/Helper/Util.php
modules/acquia_vwo_content/src/Service/Helper/Util.php
<?php
namespace Drupal\acquia_vwo_content\Service\Helper;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\RoleInterface;
/**
* Perz helper class.
*/
class Util {
/**
* Get account id.
*
* @return string|null
* Returns account id.
*/
public static function getAccountId(): ?string {
$config = \Drupal::configFactory()->get('acquia_vwo.settings');
$site_id = $config->get('id') ?? '';
return $site_id;
}
/**
* Get API key.
*
* @return string
* Returns API key.
*/
public static function getApiKey(): string {
$config = \Drupal::configFactory()->get('acquia_vwo_content.settings');
$site_id = $config->get('api.key') ?? '';
return $site_id;
}
/**
* Update data from entity settings configuration.
*
* @param array $entity_config
* The entity config.
* @param string $entity_type_id
* The entity type id.
* @param string $bundle
* The bundle of entity type.
* @param string|null $view_mode
* The view_mode of bundle.
* @param string|null $render_role
* The render role of bundle.
* @param bool $export_all
* The export all value.
*
* @return void
* Returns void.
*/
public static function updateEntityConfig(
array &$entity_config,
string $entity_type_id,
string $bundle,
?string $view_mode = NULL,
?string $render_role = NULL,
bool $export_all = FALSE,
): void {
if (!empty($view_mode) && !empty($render_role)) {
$entity_config[$entity_type_id][$bundle] = [
'view_mode' => $view_mode,
'render_role' => $render_role,
'export_all' => $export_all,
];
}
else {
if (isset($entity_config[$entity_type_id]) && is_array($entity_config[$entity_type_id])) {
if (count($entity_config[$entity_type_id]) > 1) {
unset($entity_config[$entity_type_id][$bundle]);
}
else {
unset($entity_config[$entity_type_id]);
}
}
}
}
/**
* Get view mode minimal HTML.
*
* @param \Drupal\Core\Entity\EntityInterface $object
* The content entity object.
* @param string $view_mode
* The view mode identifier.
* @param string $lang_code
* The Language code.
*
* @return array|null
* The view mode minimal HTML.
*/
public static function getViewModeMinimalHtml(EntityInterface $object, string $view_mode, string $lang_code): array|null {
$entity_type_id = $object->getEntityTypeId();
if ($entity_type_id === 'block_content') {
$build = self::getBlockMinimalBuildArray($object, $view_mode, $lang_code);
}
else {
$build = self::getViewMode($object, $view_mode, $lang_code);
}
return $build;
}
/**
* Safely switches to another account.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account to switch to.
*/
public static function switchAccountTo(AccountInterface $account): void {
\Drupal::service('account_switcher')->switchTo($account);
}
/**
* Reverts to a previous account after switching.
*/
public static function switchAccountBack(): void {
\Drupal::service('account_switcher')->switchBack();
}
/**
* Renders block using BlockViewBuilder.
*
* @param \Drupal\Core\Entity\EntityInterface $object
* The Content Entity Object.
* @param string $view_mode
* The request view mode identifier.
* @param string $lang_code
* The Language code.
*
* @return array
* Render array for the block.
*/
public static function getBlockMinimalBuildArray(EntityInterface $object, string $view_mode, string $lang_code): array {
$block = \Drupal::service('plugin.manager.block')->createInstance('block_content:' . $object->uuid());
$build = [
'#theme' => 'block',
'#attributes' => [],
'#contextual_links' => [],
'#weight' => 0,
'#configuration' => $block->getConfiguration(),
'#plugin_id' => $block->getPluginId(),
'#base_plugin_id' => $block->getBaseId(),
'#derivative_plugin_id' => $block->getDerivativeId(),
];
// Block entity itself doesn't have configuration.
$block->setConfigurationValue('view_mode', $view_mode);
$build['#configuration']['view_mode'] = $view_mode;
// See \Drupal\block\BlockViewBuilder::preRender() for reference.
$content = self::getViewMode($object, $view_mode, $lang_code);
if ($content !== NULL && !Element::isEmpty($content)) {
foreach (['#attributes', '#contextual_links'] as $property) {
if (isset($content[$property])) {
$build[$property] += $content[$property];
unset($content[$property]);
}
}
}
$build['content'] = $content;
return $build;
}
/**
* Returns the applicable render array.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The renderable entity.
* @param string $view_mode
* The view mode to render in.
* @param string $lang_code
* The Language code.
*
* @return array|null
* The render array.
*/
public static function getViewMode(EntityInterface $entity, string $view_mode, string $lang_code): array|null {
return \Drupal::entityTypeManager()
->getViewBuilder($entity->getEntityTypeId())
->view($entity, $view_mode, $lang_code);
}
/**
* Attach libraries required to render the element.
*
* @param array $page
* Array of all attachments required for page.
*/
public static function attachLibrariesForPerz(array &$page) {
$elementLibraries = \Drupal::state()->get('acquia_vwo_content.libraries', []);
foreach ($elementLibraries as $libraries) {
foreach ($libraries as $library) {
$page['#attached']['library'][] = $library;
}
}
$page['#attached']['library'][] = 'acquia_vwo_content/acquia_vwo_content';
}
/**
* Saves the required Libraries to Drupal State.
*
* @param string $entity_uuid
* UUID of the entity.
* @param array $libraries
* Array of libraries required by elements.
*/
public static function saveLibrariesForPerz(string $entity_uuid, array $libraries) {
$elementLibraries = \Drupal::state()->get('acquia_vwo_content.libraries') ?? [];
$elementLibraries[$entity_uuid] = $libraries;
\Drupal::state()->set('acquia_vwo_content.libraries', $elementLibraries);
}
/**
* Delete the required Libraries from Drupal State.
*
* @param string $entity_uuid
* UUID of the entity.
*/
public static function deleteLibrariesForPerz(string $entity_uuid) {
$elementLibraries = \Drupal::state()->get('acquia_vwo_content.libraries');
if (!empty($elementLibraries) && array_key_exists($entity_uuid, $elementLibraries)) {
unset($elementLibraries[$entity_uuid]);
\Drupal::state()->set('acquia_vwo_content.libraries', $elementLibraries);
}
}
/**
* Clears libraries from state.
*/
public static function clearLibrariesFromState() {
\Drupal::state()->set('acquia_vwo_content.libraries', NULL);
}
/**
* Checks if a config exists for a given entity type ID and bundle.
*
* @param string $entity_type_id
* The entity type ID.
* @param string $bundle
* The bundle.
*
* @return bool
* TRUE if the config exists, FALSE otherwise.
*/
public static function configExists($entity_type_id, $bundle) {
$config = \Drupal::configFactory()->get('acquia_vwo_content.entity_config');
$view_modes = $config->get('entity_config');
if (isset($view_modes[$entity_type_id]) && isset($view_modes[$entity_type_id][$bundle])) {
return TRUE;
}
return FALSE;
}
/**
* Retrieves configured view modes for an entity type and bundle.
*/
public static function getConfiguredViewModes(string $entity_type_id, string $bundle): array {
$entity_display_repository = \Drupal::service('entity_display.repository');
$view_modes = $entity_display_repository->getViewModeOptions($entity_type_id);
$configured_view_modes = [];
foreach ($view_modes as $view_mode_key => $view_mode_label) {
$view_display = \Drupal::entityTypeManager()
->getStorage('entity_view_display')
->load("{$entity_type_id}.{$bundle}.{$view_mode_key}");
if ($view_display) {
$configured_view_modes[$view_mode_key] = (string) $view_mode_label;
}
}
return $configured_view_modes;
}
/**
* Adds Acquia VWO Content settings to the form.
*/
public static function addVwoContentSettingsForm(array &$form, string $entity_type_id, string $bundle, array $configured_view_modes): void {
$config = \Drupal::service('config.factory')->getEditable(EntityHelper::ENTITY_CONFIG_NAME);
$entity_config = $config->get('entity_config');
$export_all = $entity_config[$entity_type_id][$bundle]['export_all'] ?? FALSE;
$form['acquia_vwo_content'] = [
'#type' => 'details',
'#title' => t('Acquia VWO Content Governance Settings'),
'#open' => TRUE,
'#group' => 'additional_settings',
'#weight' => 100,
];
$form['acquia_vwo_content']['enable_vwo'] = [
'#type' => 'checkbox',
'#title' => t('Make @bundle available as Acquia VWO custom widgets', ['@bundle' => $bundle]),
'#default_value' => !empty($entity_config[$entity_type_id][$bundle]),
];
$form['acquia_vwo_content']['export_all'] = [
'#type' => 'checkbox',
'#title' => t('Export all @bundle entities as VWO custom widgets', ['@bundle' => $bundle]),
'#description' => t('By default, you must choose which entities will be exported to VWO in the entity edit form. If you prefer to always export all @bundle entities to VWO, check this box.', ['@bundle' => $bundle]),
'#default_value' => $export_all,
'#states' => [
'visible' => [
':input[name="enable_vwo"]' => ['checked' => TRUE],
],
],
];
$form['acquia_vwo_content']['view_mode'] = [
'#type' => 'select',
'#title' => t('Render View Mode'),
'#options' => $configured_view_modes,
'#default_value' => $entity_config[$entity_type_id][$bundle]['view_mode'] ?? 'default',
'#description' => t('Select the view mode to use when exporting entities to VWO.'),
'#states' => [
'visible' => [
':input[name="enable_vwo"]' => ['checked' => TRUE],
],
],
];
$form['acquia_vwo_content']['render_role'] = [
'#type' => 'select',
'#title' => t('Render Role'),
'#description' => t('Select the role to use when exporting entities to VWO.'),
'#options' => self::getUserRoleOptions(),
'#default_value' => $entity_config[$entity_type_id][$bundle]['render_role'] ?? RoleInterface::ANONYMOUS_ID,
'#states' => [
'visible' => [
':input[name="enable_vwo"]' => ['checked' => TRUE],
],
],
];
$form['actions']['submit']['#submit'][] = 'acquia_vwo_content_entity_settings_form_submit';
}
/**
* Handles content entity form alterations.
*/
public static function handleContentEntityForm(array &$form, ContentEntityInterface $entity, string $form_id): void {
if (!self::configExists($entity->getEntityTypeId(), $entity->bundle())) {
return;
}
if (str_contains($form_id, '_delete_form')) {
$form['acquia_vwo_delete_message'] = [
'#type' => 'markup',
'#markup' => t(' This content will also be deleted from the VWO Custom Widgets Library.'),
];
return;
}
$config = \Drupal::configFactory()->get('acquia_vwo_content.entity_config');
$entity_config = $config->get('entity_config');
$export_all = $entity_config[$entity->getEntityTypeId()][$entity->bundle()]['export_all'] ?? FALSE;
$is_marked_for_export = \Drupal::service('acquia_vwo_content.acquia_vwo_storage')
->isMarkedForExport($entity->uuid());
$form['acquia_vwo_content'] = [
'#type' => 'details',
'#title' => t('Acquia VWO Content Governance'),
'#group' => 'advanced',
'#weight' => -100,
'#open' => TRUE,
];
$form['acquia_vwo_content']['field_acquia_vwo_export'] = [
'#type' => 'checkbox',
'#title' => t('Export to VWO as Custom Widget.'),
'#default_value' => $export_all ? 1 : $is_marked_for_export,
'#description' => t('Check this box to send this content to VWO as a Custom Widget.'),
];
if ($export_all) {
$form['acquia_vwo_content']['field_acquia_vwo_export']['#disabled'] = TRUE;
$form['acquia_vwo_content']['field_acquia_vwo_export']['#description'] = t('All @bundle entities are currently configured to be exported to VWO. If you prefer to configure each entity individually, please disable the "export all" option in Acquia VWO Content Governance settings.', ['@bundle' => $entity->bundle()]);
}
array_unshift($form['actions']['submit']['#submit'], 'acquia_vwo_content_form_submit');
}
/**
* Retrieves available user roles.
*/
public static function getUserRoleOptions(): array {
$roles = \Drupal::entityTypeManager()->getStorage('user_role')->loadMultiple();
$options = [];
foreach ($roles as $role) {
$options[$role->id()] = $role->label();
}
return $options;
}
}
