ShareMessageViewBuilder.php in Share Message 8
File
src/Entity/Handler/ShareMessageViewBuilder.php
View source
<?php
namespace Drupal\sharemessage\Entity\Handler;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityViewBuilder;
class ShareMessageViewBuilder extends EntityViewBuilder {
public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
$build = $this
->viewMultiple([
$entity,
], $view_mode, $langcode);
return reset($build);
}
public function viewMultiple(array $entities = [], $view_mode = 'full', $langcode = NULL) {
if (empty($entities)) {
return [];
}
$build = [];
foreach ($entities as $entity) {
$cacheability_metadata = CacheableMetadata::createFromObject($entity);
$build[$entity
->id()] = [
'#sharemessage' => $entity,
'#contextual_links' => [
'sharemessage' => [
'route_parameters' => [
'sharemessage' => $entity
->id(),
],
],
],
];
$cacheability_metadata
->addCacheableDependency(\Drupal::config('sharemessage.settings'));
$cacheability_metadata
->applyTo($build[$entity
->id()]);
$context = $entity
->getContext($view_mode);
$is_overridden = \Drupal::request()->query
->get('smid') && \Drupal::config('sharemessage.settings')
->get('message_enforcement');
$og_view_modes = [
'full',
'only_og_tags',
'no_attributes',
];
if (!$is_overridden && in_array($context['view_mode'], $og_view_modes)) {
$build[$entity
->id()]['#attached']['html_head'] = $this
->mapHeadElements($entity
->buildOGTags($context));
}
if (\Drupal::config('sharemessage.settings')
->get('add_twitter_card')) {
$twitter_tags = $entity
->buildTwitterCardTags($context);
$build[$entity
->id()]['#attached']['html_head'] = array_merge($build[$entity
->id()]['#attached']['html_head'], $twitter_tags);
}
if ($entity
->hasPlugin() && $view_mode != 'only_og_tags') {
$attributes_view_modes = [
'full',
'attributes_only',
];
$plugin_attributes = in_array($context['view_mode'], $attributes_view_modes);
$build[$entity
->id()][$entity
->getPluginID()] = $entity
->getPlugin()
->build($context, $plugin_attributes);
}
}
return $build;
}
protected function mapHeadElements(array $elements) {
$mapped = [];
foreach ($elements as $element) {
$mapped[] = [
$element,
str_replace(':', '_', $element['#attributes']['property']),
];
}
return $mapped;
}
}