Skip to content
Merged

Dev2 #392

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app/frontend/controllers/SiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ public function actionIndex($feature = null): string

$queryParams = Yii::$app->request->queryParams;
$sort = Yii::$app->request->get('sort');
$results = $this->service->index();
$user_id = (int)Yii::$app->user->getId();
$results = $this->service->index($user_id);

try {
if ($form->load($queryParams) && $form->validate()) {
Expand All @@ -129,7 +130,7 @@ public function actionIndex($feature = null): string
Yii::$app->request->setQueryParams($newParams);
}

$results = $this->service->search($form);
$results = $this->service->search($form, $user_id);
}
} catch (ResponseException $e) {
$errorQueryMessage = "Задан неправильный поисковый запрос. Синтаксическая ошибка — использована недопустимая последовательность символов при составлении
Expand Down
12 changes: 9 additions & 3 deletions app/frontend/views/site/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,16 @@


$total_count = $results->indexed_documents !== 0 ? $results->indexed_documents : $results->getTotalCount();
// var_dump($results->indexed_documents);
$pagination_total_count = $total_count;

if ($results->maxMatches !== null) {
$pagination_total_count = $results->maxMatches;
}

$pagination = new Pagination(
[
'totalCount' => $total_count,
'totalCount' => $pagination_total_count,
'defaultPageSize' => Yii::$app->params['questions']['pageSize'],
]
);
Expand Down Expand Up @@ -199,7 +205,7 @@
<?php else : ?>
<div class="row">
<div class="col-md-8 d-flex align-items-center">
<?= CommentSummary::widget(['pagination' => $pagination]); ?>
<?= CommentSummary::widget(['pagination' => $pagination, 'totalCount' => $total_count]); ?>
</div>
<div class="col-md-4">
<div class="d-flex align-items-start ">
Expand Down Expand Up @@ -235,7 +241,7 @@
<div>
<?= DateHelper::showDateFromTimestamp($comment->datetime); ?>, <?= \App\helpers\SearchResultsHelper::showUsername($comment); ?>
</div>
<div><?= SearchContext::widget(['comment' => $comment, 'pagination' => $pagination]); ?></div>
<div><?= SearchContext::widget(['comment' => $comment, 'pagination' => $pagination, 'userId' => Yii::$app->user->id]); ?></div>
</div>
</div>

Expand Down
20 changes: 16 additions & 4 deletions app/frontend/widgets/question/CommentSummary.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,33 @@
class CommentSummary extends Widget
{
public Pagination $pagination;
private int $totalCount;
public ?int $totalCount = null;

public function init()
{
$this->totalCount = $this->pagination->totalCount;
parent::init();

// Если totalCount не передан явно, используем значение из пагинации
if ($this->totalCount === null) {
$this->totalCount = $this->pagination->totalCount;
}
}

public function renderSummary(): string
{
$totalCount = $this->pagination->totalCount;
$totalCount = $this->totalCount;
$start = (($this->pagination->getPage() + 1) * $this->pagination->pageSize - $this->pagination->pageSize) + 1;
$end = ($this->pagination->getPage() + 1) * $this->pagination->pageSize;

// Если end превышает общее количество, корректируем
if ($end > $totalCount) {
$end = $totalCount;
}

// Если start превышает общее количество (например, при последней странице с малым количеством элементов)
if ($start > $totalCount) {
$start = $totalCount;
}

$string = $this->getTotalString($totalCount, $start, $end);
return Html::tag('p', $string, ['class' => 'summary']);
Expand Down Expand Up @@ -53,4 +65,4 @@ public function getTotalString($totalCount, $start, $end): string

return $string;
}
}
}
32 changes: 25 additions & 7 deletions app/frontend/widgets/search/SearchContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,22 @@ class SearchContext extends Widget
private mixed $position;

public Pagination $pagination;

/**
* @var string|null ID пользователя. Если передан - returnUrl = true, если null - returnUrl = false
*/
public ?string $userId = null;

/**
* @var bool Приватный параметр, определяется автоматически по наличию userId
*/
private bool $returnUrl = false;

public function init(): void
{
// Определяем returnUrl на основе наличия userId
$this->returnUrl = $this->userId !== null && $this->userId !== '';

$this->title = $this->comment->type === Comment::LINKED_QUESTION
? (string) $this->comment->parent_id
: (string) $this->comment->data_id;
Expand Down Expand Up @@ -61,12 +74,17 @@ public function run(): string
return Html::tag('span', '');
}

$link = Html::a(
$this->title,
$this->getUrl(),
['rel' => 'nofollow noindex']
);
// Если нужно вернуть заголовок со ссылкой (для зарегистрированных пользователей)
if ($this->returnUrl) {
$link = Html::a(
$this->title,
$this->getUrl(),
['rel' => 'nofollow noindex']
);
return $link;
}

return $link;
// Если нужно вернуть только текст заголовка без ссылки (для незарегистрированных)
return Html::encode($this->title);
}
}
}
28 changes: 24 additions & 4 deletions app/src/repositories/Question/QuestionDataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,21 @@

class QuestionDataProvider extends BaseDataProvider
{

/**
* @var string|callable Имя столбца с ключом или callback-функция, возвращающие его
*/
public $key;

/**
* @var Search
*/
public Search $query;


/**
* @var int|null Максимальное количество результатов. Если null, используется текущий подсчет
*/
public ?int $maxMatches = null;

public string $suggestQueryString = '';
public int $indexed_documents = 0;

Expand Down Expand Up @@ -54,7 +59,13 @@ protected function prepareModels(): array
$this->query->offset($offset);

$maxMatches = $offset + $limit;
// Устанавливаем max_matches в зависимости от номера выбранной старницы

// Если передан maxMatches, используем переданное значение, иначе вычисляем
if ($this->maxMatches !== null) {
$maxMatches = min($this->maxMatches, $maxMatches);
}

// Устанавливаем max_matches
$this->query->maxMatches($maxMatches);

$data = $this->query->get();
Expand Down Expand Up @@ -103,7 +114,16 @@ protected function prepareKeys($models): array

protected function prepareTotalCount()
{
// Сохраняем оригинальные настройки запроса
$originalMaxMatches = $this->maxMatches;

// Временно устанавливаем maxMatches для подсчета общего количества
if ($this->maxMatches !== null) {
$this->query->maxMatches($this->maxMatches);
}

$count = $this->query->get()->getTotal();

return $count;
}
}
}
6 changes: 4 additions & 2 deletions app/src/services/ManticoreService.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __construct(QuestionRepository $questionRepository, SuggestionSe
* @return QuestionDataProvider
* @throws EmptySearchRequestExceptions
*/
public function search(SearchForm $form): QuestionDataProvider
public function search(SearchForm $form, ?int $user_id): QuestionDataProvider
{
$indexName = $this->getSearchIndexName($form);
$queryString = $form->query;
Expand Down Expand Up @@ -76,6 +76,7 @@ public function search(SearchForm $form): QuestionDataProvider
return new QuestionDataProvider(
[
'query' => $comments,
'maxMatches' => $user_id ? null : 1000,
'pagination' => [
'pageSize' => Yii::$app->params['questions']['pageSize'],
],
Expand All @@ -95,7 +96,7 @@ public function search(SearchForm $form): QuestionDataProvider
);
}

public function index(): QuestionDataProvider
public function index(?int $user_id): QuestionDataProvider
{
$form = new SearchForm();
$indexName = $this->getSearchIndexName($form);
Expand All @@ -104,6 +105,7 @@ public function index(): QuestionDataProvider
return new QuestionDataProvider(
[
'query' => $comments,
'maxMatches' => $user_id ? null : 1000,
'pagination' => [
'pageSize' => Yii::$app->params['questions']['pageSize'],
],
Expand Down