Same name in other branches
- 8.x-1.x src/EasyBreadcrumbStructuredDataJsonLd.php \Drupal\easy_breadcrumb\EasyBreadcrumbStructuredDataJsonLd::value()
Build JSON-LD value.
Fichier
-
src/
EasyBreadcrumbStructuredDataJsonLd.php, line 80
Classe
- EasyBreadcrumbStructuredDataJsonLd
- Class EasyBreadcrumbStructuredDataJsonLd.
Namespace
Drupal\easy_breadcrumbCode
public function value() {
$value = FALSE;
$config = $this->configFactory
->get(EasyBreadcrumbConstants::MODULE_SETTINGS);
if ($config->get(EasyBreadcrumbConstants::ADD_STRUCTURED_DATA_JSON_LD)) {
/** @var \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb */
$breadcrumb = $this->easyBreadcrumbBuilder
->build($this->routeMatch);
// Allow modules to alter the breadcrumb.
$context = [
'builder' => $this->easyBreadcrumbBuilder,
];
$this->moduleHandler
->alter('system_breadcrumb', $breadcrumb, $this->routeMatch, $context);
$links = $breadcrumb->getLinks();
// Only fire if at least one link present.
if (count($links) > 0) {
// Open JSON.
$value = '{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [';
$position = 1;
/** @var \Drupal\Core\Link $link */
foreach ($links as $link) {
$name = $link->getText();
$item = $link->getUrl()
->setAbsolute(TRUE)
->toString();
// Escape " to produce valid json for titles with "" in them.
$name = str_replace('"', '\\"', $name);
$item = str_replace('"', '\\"', $item);
// Add a comma before each item except the first.
if ($position > 1) {
$value .= ',';
}
// Only add item if link's not empty.
if (!empty($item)) {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '",
"item": "' . $item . '"
}';
}
else {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '"
}';
}
// Increment position for next run.
$position++;
}
// Close JSON.
$value .= ']}';
}
}
return $value;
}