EasyBreadcrumbStructuredDataJsonLd.php in Easy Breadcrumb 2.x
File
src/EasyBreadcrumbStructuredDataJsonLd.php
View source
<?php
namespace Drupal\easy_breadcrumb;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EasyBreadcrumbStructuredDataJsonLd implements ContainerInjectionInterface {
protected $easyBreadcrumbBuilder;
protected $configFactory;
protected $routeMatch;
public function __construct(EasyBreadcrumbBuilder $easy_breadcrumb_builder, ConfigFactoryInterface $config_factory, RouteMatchInterface $route_match) {
$this->easyBreadcrumbBuilder = $easy_breadcrumb_builder;
$this->configFactory = $config_factory;
$this->routeMatch = $route_match;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('easy_breadcrumb.breadcrumb'), $container
->get('config.factory'), $container
->get('current_route_match'));
}
public function value() {
$value = FALSE;
$config = $this->configFactory
->get(EasyBreadcrumbConstants::MODULE_SETTINGS);
if ($config
->get(EasyBreadcrumbConstants::ADD_STRUCTURED_DATA_JSON_LD)) {
$breadcrumb = $this->easyBreadcrumbBuilder
->build($this->routeMatch);
$links = $breadcrumb
->getLinks();
if (count($links) > 0) {
$value = '{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [';
$position = 1;
foreach ($links as $link) {
$name = $link
->getText();
$item = $link
->getUrl()
->setAbsolute(TRUE)
->toString();
$name = str_replace('"', '\\"', $name);
$item = str_replace('"', '\\"', $item);
if ($position > 1) {
$value .= ',';
}
if (!empty($item)) {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '",
"item": "' . $item . '"
}';
}
else {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '"
}';
}
$position++;
}
$value .= ']}';
}
}
return $value;
}
}