View source
<?php
namespace Drupal\path_alias;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Language\LanguageInterface;
class AliasRepository implements AliasRepositoryInterface {
protected $connection;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function preloadPathAlias($preloaded, $langcode) {
$select = $this
->getBaseQuery()
->fields('base_table', [
'path',
'alias',
]);
if (!empty($preloaded)) {
$conditions = $this->connection
->condition('OR');
foreach ($preloaded as $preloaded_item) {
$conditions
->condition('base_table.path', $this->connection
->escapeLike($preloaded_item), 'LIKE');
}
$select
->condition($conditions);
}
$this
->addLanguageFallback($select, $langcode);
$select
->orderBy('base_table.id', 'ASC');
return $select
->execute()
->fetchAllKeyed();
}
public function lookupBySystemPath($path, $langcode) {
$select = $this
->getBaseQuery()
->fields('base_table', [
'id',
'path',
'alias',
'langcode',
])
->condition('base_table.path', $this->connection
->escapeLike($path), 'LIKE');
$this
->addLanguageFallback($select, $langcode);
$select
->orderBy('base_table.id', 'DESC');
return $select
->execute()
->fetchAssoc() ?: NULL;
}
public function lookupByAlias($alias, $langcode) {
$select = $this
->getBaseQuery()
->fields('base_table', [
'id',
'path',
'alias',
'langcode',
])
->condition('base_table.alias', $this->connection
->escapeLike($alias), 'LIKE');
$this
->addLanguageFallback($select, $langcode);
$select
->orderBy('base_table.id', 'DESC');
return $select
->execute()
->fetchAssoc() ?: NULL;
}
public function pathHasMatchingAlias($initial_substring) {
$query = $this
->getBaseQuery();
$query
->addExpression(1);
return (bool) $query
->condition('base_table.path', $this->connection
->escapeLike($initial_substring) . '%', 'LIKE')
->range(0, 1)
->execute()
->fetchField();
}
protected function getBaseQuery() {
$query = $this->connection
->select('path_alias', 'base_table');
$query
->condition('base_table.status', 1);
return $query;
}
protected function addLanguageFallback(SelectInterface $query, $langcode) {
$langcode_list = [
$langcode,
LanguageInterface::LANGCODE_NOT_SPECIFIED,
];
if ($langcode === LanguageInterface::LANGCODE_NOT_SPECIFIED) {
array_pop($langcode_list);
}
elseif ($langcode > LanguageInterface::LANGCODE_NOT_SPECIFIED) {
$query
->orderBy('base_table.langcode', 'DESC');
}
else {
$query
->orderBy('base_table.langcode', 'ASC');
}
$query
->condition('base_table.langcode', $langcode_list, 'IN');
}
}