ViewModesInventoryFactory.php in View Modes Inventory - Bootstrap Ready 8.2
File
src/ViewModesInventoryFactory.php
View source
<?php
namespace Drupal\vmi;
use Symfony\Component\Yaml\Yaml;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ViewModesInventoryFactory implements ContainerInjectionInterface {
use StringTranslationTrait;
protected $configFactory;
protected $moduleHandler;
public function __construct(ConfigFactoryInterface $config_factory, TranslationInterface $translation, ModuleHandlerInterface $module_handler) {
$this->configFactory = $config_factory;
$this->stringTranslation = $translation;
$this->moduleHandler = $module_handler;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'), $container
->get('string_translation'), $container
->get('module_handler'));
}
public function getViewModesList() {
$module_path = $this->moduleHandler
->getModule('vmi')
->getPath();
$vmi_filename = DRUPAL_ROOT . '/' . $module_path . '/src/assets/view_modes.list.vmi.yml';
if (is_file($vmi_filename)) {
$vmi_list = (array) Yaml::parse(file_get_contents($vmi_filename));
return $vmi_list;
}
else {
$lookup_message = $this
->t('View modes inventory layouts list file does not exist!');
throw new \Exception($lookup_message);
}
}
public function getLayoutsMapping() {
$module_path = $this->moduleHandler
->getModule('vmi')
->getPath();
$vmi_layout_filename = DRUPAL_ROOT . '/' . $module_path . '/src/assets/layouts.mapping.vmi.yml';
if (is_file($vmi_layout_filename)) {
$vmi_layout_list = (array) Yaml::parse(file_get_contents($vmi_layout_filename));
return $vmi_layout_list;
}
else {
$lookup_message = $this
->t('View modes inventory layouts list file does not exist!');
throw new \Exception($lookup_message);
}
}
public function mapViewModeWithLayout($selected_view_mode, $default_mapped_layout, $entity_type, $bundle_name, $config_template_file, $config_name) {
$real_config_name = str_replace('CONTENT_TYPE_NAME', $bundle_name, $config_name);
$view_mode_config = $this->configFactory
->getEditable($real_config_name);
$module_path = $this->moduleHandler
->getModule('vmi')
->getPath();
$full_config_template_file = DRUPAL_ROOT . '/' . $module_path . $config_template_file;
$config_template_content = file_get_contents($full_config_template_file);
$real_config_template_content = str_replace('CONTENT_TYPE_NAME', $bundle_name, $config_template_content);
$real_config_template_content_data = (array) Yaml::parse($real_config_template_content);
$view_mode_config
->setData($real_config_template_content_data)
->save();
}
}