SvgEmbedProcess.php in SVG Embed 2.0.x
File
src/SvgEmbedProcess.php
View source
<?php
namespace Drupal\svg_embed;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\file\Entity\File;
use SimpleXMLElement;
class SvgEmbedProcess implements SvgEmbedProcessInterface {
protected $entityTypeManager;
protected $moduleHandler;
protected $connection;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, Connection $connection) {
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->connection = $connection;
}
public function translate($uuid, $langcode) : string {
$xml = $this
->loadFile($uuid);
if ($this->moduleHandler
->moduleExists('locale')) {
$this
->embedTranslate($xml, $langcode);
}
$svg = $xml
->asXML();
$svg_tag = strpos($svg, '<svg');
return substr($svg, $svg_tag);
}
private function loadFile($uuid) : SimpleXMLElement {
$text = '';
try {
if ($file = $this->entityTypeManager
->getStorage('file')
->loadByProperties([
'uuid' => $uuid,
])) {
$text = file_get_contents($file
->getFileUri());
}
} catch (InvalidPluginDefinitionException $e) {
} catch (PluginNotFoundException $e) {
}
return new SimpleXMLElement($text);
}
protected function embedTranslate($xml, $langcode) : void {
foreach ($xml as $child) {
$this
->embedTranslate($child, $langcode);
if (isset($child->text) || isset($child->tspan)) {
if (isset($child->text->tspan)) {
$text = $child->text->tspan;
}
elseif (isset($child->tspan)) {
$text = $child->tspan;
}
else {
$text = $child->text;
}
$i = 0;
while (TRUE) {
$string = (string) $text[$i];
if (empty($string)) {
break;
}
$string = trim($string);
if (!empty($string)) {
$query = $this->connection
->select('locales_source', 's');
$query
->leftJoin('locales_target', 't', 's.lid = t.lid');
$translation = $query
->fields('t', [
'translation',
])
->condition('s.source', $string)
->condition('s.textgroup', 'svg_embed')
->condition('t.language', $langcode)
->execute()
->fetchField();
$text[$i][0] = empty($translation) ? $string : $translation;
}
$i++;
}
}
}
}
}