StringDatabaseStorageDecorator.php in Language Hierarchy 2.x
File
src/StringDatabaseStorageDecorator.php
View source
<?php
namespace Drupal\language_hierarchy;
use Drupal\Core\Database\Connection;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\locale\StringDatabaseStorage;
use Drupal\locale\StringStorageInterface;
class StringDatabaseStorageDecorator extends StringDatabaseStorage {
use DependencySerializationTrait;
protected $stringStorage;
protected $languageManager;
public function __construct(StringStorageInterface $string_storage, LanguageManagerInterface $language_manager, Connection $connection, array $options = []) {
$this->stringStorage = $string_storage;
$this->languageManager = $language_manager;
parent::__construct($connection, $options);
}
public function __call($method, array $args) {
return call_user_func_array([
$this->stringStorage,
$method,
], $args);
}
protected function dbStringLoad(array $conditions, array $options, $class) {
$strings = parent::dbStringLoad($conditions, $options, $class);
if (!empty($conditions['language']) && is_scalar($conditions['language'])) {
$filtered = [];
foreach ($strings as $string) {
$lid = $string
->getId();
if (!isset($filtered[$lid])) {
$filtered[$lid] = $string;
}
}
$strings = array_values($filtered);
}
return $strings;
}
protected function dbStringSelect(array $conditions, array $options = []) {
$query = $this->stringStorage
->dbStringSelect($conditions, $options);
if (!isset($conditions['translated'])) {
$tables =& $query
->getTables();
if (isset($tables['t']['arguments'][':langcode'])) {
$attempted_langcode = $tables['t']['arguments'][':langcode'];
$candidates = array_values($this->languageManager
->getFallbackCandidates([
'langcode' => $attempted_langcode,
'operation' => 'locale_lookup',
]));
if ($candidates) {
$candidates = array_merge([
$attempted_langcode,
], $candidates);
$tables['t']['condition'] = "t.lid = s.lid AND t.language IN (:langcode[])";
unset($tables['t']['arguments'][':langcode']);
$tables['t']['arguments'][':langcode[]'] = $candidates;
$query
->addJoin('LEFT', 'language_hierarchy_priority', 'lhp', 't.language = lhp.langcode');
$query
->orderBy('lhp.priority', 'DESC');
}
}
}
return $query;
}
}