BlazyStyleBaseTrait.php in Blazy 8
File
src/Dejavu/BlazyStyleBaseTrait.php
View source
<?php
namespace Drupal\blazy\Dejavu;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Render\Markup;
use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\blazy\Blazy;
use Drupal\blazy\BlazyDefault;
trait BlazyStyleBaseTrait {
protected $firstImage;
protected $htmlSettings = [];
protected $blazyManager;
public function blazyManager() {
return $this->blazyManager;
}
protected function buildSettings() {
$view = $this->view;
$count = count($view->result);
$settings = $this->options;
$view_name = $view->storage
->id();
$view_mode = $view->current_display;
$plugin_id = $this
->getPluginId();
$instance = str_replace('_', '-', "{$view_name}-{$view_mode}");
$id = empty($settings['id']) ? '' : $settings['id'];
$id = Blazy::getHtmlId("{$plugin_id}-views-{$instance}", $id);
$settings += [
'cache_metadata' => [
'keys' => [
$id,
$view_mode,
$count,
],
],
] + BlazyDefault::lazySettings();
$settings['check_blazy'] = TRUE;
$settings['id'] = $id;
$settings['cache_tags'] = $view
->getCacheTags();
$settings['count'] = $count;
$settings['current_view_mode'] = $view_mode;
$settings['instance_id'] = $instance;
$settings['multiple'] = TRUE;
$settings['plugin_id'] = $plugin_id;
$settings['use_ajax'] = $view
->ajaxEnabled();
$settings['view_name'] = $view_name;
$settings['view_display'] = $view->style_plugin->displayHandler
->getPluginId();
$settings['_views'] = TRUE;
if (!empty($this->htmlSettings)) {
$settings = NestedArray::mergeDeep($settings, $this->htmlSettings);
}
$this
->blazyManager()
->getModuleHandler()
->alter('blazy_settings_views', $settings, $view);
return $settings;
}
protected function setHtmlSettings(array $settings = []) {
$this->htmlSettings = $settings;
return $this;
}
public function getFirstImage($row) {
if (!isset($this->firstImage)) {
$rendered = [];
if ($row && isset($row->_entity) && ($fields = $row->_entity
->getFields(FALSE))) {
foreach ($fields as $field) {
if ($field
->getFieldDefinition()
->getFieldStorageDefinition()
->getSetting('target_type') == 'media') {
$name = $field
->getName();
break;
}
if ($field
->first() instanceof ImageItem) {
$name = $field
->getName();
break;
}
}
if (isset($name) && ($rendered = $this
->getFieldRenderable($row, 0, $name))) {
if (is_array($rendered) && isset($rendered['rendered']) && !$rendered['rendered'] instanceof Markup) {
$rendered = isset($rendered['rendered']['#build']) ? $rendered['rendered']['#build'] : [];
}
}
}
$this->firstImage = $rendered;
}
return $this->firstImage;
}
public function getFieldRenderable($row, $index, $field_name = '', $multiple = FALSE) {
if (empty($field_name)) {
return FALSE;
}
$result = isset($this->view->field[$field_name]) ? $this->view->field[$field_name]
->getItems($row) : [];
return empty($result) ? [] : ($multiple ? $result : $result[0]);
}
}