-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
BaseListView.php
739 lines (644 loc) · 22.7 KB
/
BaseListView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
<?php
declare(strict_types=1);
namespace Yiisoft\Yii\DataView;
use InvalidArgumentException;
use Stringable;
use Yiisoft\Data\Paginator\KeysetPaginator;
use Yiisoft\Data\Paginator\OffsetPaginator;
use Yiisoft\Data\Paginator\PageNotFoundException;
use Yiisoft\Data\Paginator\PageToken;
use Yiisoft\Data\Paginator\PaginatorInterface;
use Yiisoft\Data\Reader\CountableDataInterface;
use Yiisoft\Data\Reader\Filter\All;
use Yiisoft\Data\Reader\FilterableDataInterface;
use Yiisoft\Data\Reader\FilterInterface;
use Yiisoft\Data\Reader\LimitableDataInterface;
use Yiisoft\Data\Reader\OffsetableDataInterface;
use Yiisoft\Data\Reader\ReadableDataInterface;
use Yiisoft\Data\Reader\Sort;
use Yiisoft\Data\Reader\SortableDataInterface;
use Yiisoft\Html\Html;
use Yiisoft\Html\Tag\Div;
use Yiisoft\Html\Tag\Td;
use Yiisoft\Translator\CategorySource;
use Yiisoft\Translator\IdMessageReader;
use Yiisoft\Translator\IntlMessageFormatter;
use Yiisoft\Translator\SimpleMessageFormatter;
use Yiisoft\Translator\Translator;
use Yiisoft\Translator\TranslatorInterface;
use Yiisoft\Validator\Result as ValidationResult;
use Yiisoft\Widget\Widget;
use Yiisoft\Data\Reader\OrderHelper;
use Yiisoft\Yii\DataView\Exception\DataReaderNotSetException;
/**
* @psalm-type UrlArguments = array<string,scalar|Stringable|null>
* @psalm-type UrlCreator = callable(UrlArguments,array):string
* @psalm-type PageNotFoundExceptionCallback = callable(PageNotFoundException):void
* @psalm-import-type TOrder from Sort
*/
abstract class BaseListView extends Widget
{
/**
* @psalm-var UrlCreator|null
*/
protected $urlCreator = null;
protected UrlConfig $urlConfig;
protected int $defaultPageSize = PaginatorInterface::DEFAULT_PAGE_SIZE;
/**
* A name for {@see CategorySource} used with translator ({@see TranslatorInterface}) by default.
* @psalm-suppress MissingClassConstType
*/
final public const DEFAULT_TRANSLATION_CATEGORY = 'yii-dataview';
/**
* @var TranslatorInterface A translator instance used for translations of messages. If it was not set
* explicitly in the constructor, a default one created automatically in {@see createDefaultTranslator()}.
*/
protected readonly TranslatorInterface $translator;
/**
* @psalm-var non-empty-string|null
*/
private ?string $containerTag = 'div';
private array $containerAttributes = [];
/**
* @psalm-var non-empty-string|null
*/
private ?string $summaryTag = 'div';
private array $summaryAttributes = [];
private ?string $summaryTemplate = 'Page <b>{currentPage}</b> of <b>{totalPages}</b>';
protected ?string $emptyText = null;
private array $emptyTextAttributes = [];
private string $header = '';
private array $headerAttributes = [];
private string $layout = "{header}\n{toolbar}\n{items}\n{summary}\n{pager}";
private string|OffsetPagination|KeysetPagination|null $pagination = null;
protected ?ReadableDataInterface $dataReader = null;
private string $toolbar = '';
/**
* @psalm-var array<string,scalar|Stringable|null>
*/
protected array $urlArguments = [];
protected array $urlQueryParameters = [];
protected UrlParameterProviderInterface|null $urlParameterProvider = null;
private bool $ignoreMissingPage = true;
protected bool $enableMultiSort = false;
/**
* @psalm-var PageNotFoundExceptionCallback|null
*/
private $pageNotFoundExceptionCallback = null;
protected ?ReadableDataInterface $preparedDataReader = null;
public function __construct(
TranslatorInterface|null $translator = null,
protected readonly string $translationCategory = self::DEFAULT_TRANSLATION_CATEGORY,
) {
$this->translator = $translator ?? $this->createDefaultTranslator();
$this->urlConfig = new UrlConfig();
}
/**
* @psalm-param UrlCreator|null $urlCreator
*/
final public function urlCreator(?callable $urlCreator): static
{
$new = clone $this;
$new->urlCreator = $urlCreator;
return $new;
}
final public function ignoreMissingPage(bool $value): static
{
$new = clone $this;
$new->ignoreMissingPage = $value;
return $new;
}
/**
* @psalm-param PageNotFoundExceptionCallback|null $callback
*/
final public function pageNotFoundExceptionCallback(?callable $callback): static
{
$new = clone $this;
$new->pageNotFoundExceptionCallback = $callback;
return $new;
}
/**
* Return a new instance with name of argument or query parameter for page.
*
* @param string $name The name of argument or query parameter for page.
*/
final public function pageParameterName(string $name): static
{
$new = clone $this;
$new->urlConfig = $this->urlConfig->withPageParameterName($name);
return $new;
}
final public function previousPageParameterName(string $name): static
{
$new = clone $this;
$new->urlConfig = $this->urlConfig->withPreviousPageParameterName($name);
return $new;
}
/**
* Return a new instance with name of argument or query parameter for page size.
*
* @param string $name The name of argument or query parameter for page size.
*/
final public function pageSizeParameterName(string $name): static
{
$new = clone $this;
$new->urlConfig = $this->urlConfig->withPageSizeParameterName($name);
return $new;
}
final public function urlParameterProvider(?UrlParameterProviderInterface $provider): static
{
$new = clone $this;
$new->urlParameterProvider = $provider;
return $new;
}
final public function enableMultiSort(bool $value = true): self
{
$new = clone $this;
$new->enableMultiSort = $value;
return $new;
}
/**
* Renders the data models.
*
* @return string The rendering result.
*
* @psalm-param array<array-key, array|object> $items
*/
abstract protected function renderItems(array $items, ValidationResult $filterValidationResult): string;
final public function containerTag(?string $tag): static
{
if ($tag === '') {
throw new InvalidArgumentException('Tag name cannot be empty.');
}
$new = clone $this;
$new->containerTag = $tag;
return $new;
}
/**
* Returns a new instance with the HTML attributes for container.
*
* @param array $attributes Attribute values indexed by attribute names.
*/
final public function containerAttributes(array $attributes): static
{
$new = clone $this;
$new->containerAttributes = $attributes;
return $new;
}
/**
* Return a new instance with the empty text.
*
* @param ?string $emptyText The HTML content to be displayed when {@see dataProvider} does not have any data.
*
* The default value is the text "No results found." which will be translated to the current application language.
*
* {@see notShowOnEmpty()}
* {@see emptyTextAttributes()}
*/
public function emptyText(?string $emptyText): static
{
$new = clone $this;
$new->emptyText = $emptyText;
return $new;
}
/**
* Returns a new instance with the HTML attributes for the empty text.
*
* @param array $values Attribute values indexed by attribute names.
*/
public function emptyTextAttributes(array $values): static
{
$new = clone $this;
$new->emptyTextAttributes = $values;
return $new;
}
public function getDataReader(): ReadableDataInterface
{
if ($this->dataReader === null) {
throw new DataReaderNotSetException();
}
return $this->dataReader;
}
/**
* @return array The array with format:
* ```
* [
* FilterInterface[]|null, // Array of filters or `null` if there are definitely no entries for the current filter
* ValidationResult, // Validation result of the filter
* ]
* ```
*
* @psalm-return list{FilterInterface[]|null,ValidationResult}
*/
protected function makeFilters(): array
{
return [[], new ValidationResult()];
}
/**
* @param FilterInterface[] $filters
*
* @throws PageNotFoundException
*
* @psalm-return array<array-key, array|object>
*/
private function prepareDataReaderAndGetItems(array $filters): array
{
$page = $this->urlParameterProvider?->get(
$this->urlConfig->getPageParameterName(),
$this->urlConfig->getPageParameterType()
);
$previousPage = $this->urlParameterProvider?->get(
$this->urlConfig->getPreviousPageParameterName(),
$this->urlConfig->getPreviousPageParameterType(),
);
$pageSize = $this->urlParameterProvider?->get(
$this->urlConfig->getPageSizeParameterName(),
$this->urlConfig->getPageSizeParameterType(),
);
$sort = $this->urlParameterProvider?->get(
$this->urlConfig->getSortParameterName(),
$this->urlConfig->getSortParameterType(),
);
$this->preparedDataReader = $this->prepareDataReaderByParams($page, $previousPage, $pageSize, $sort, $filters);
try {
return $this->getItems($this->preparedDataReader);
} catch (PageNotFoundException $exception) {
}
if ($this->ignoreMissingPage) {
$this->preparedDataReader = $this->prepareDataReaderByParams(null, null, $pageSize, $sort, $filters);
try {
return $this->getItems($this->preparedDataReader);
} catch (PageNotFoundException $exception) {
}
}
if ($this->pageNotFoundExceptionCallback !== null) {
($this->pageNotFoundExceptionCallback)($exception);
}
throw $exception;
}
/**
* @throws PageNotFoundException
*
* @psalm-return array<array-key, array|object>
*/
private function getItems(ReadableDataInterface $dataReader): array
{
$items = $dataReader->read();
return is_array($items) ? $items : iterator_to_array($items);
}
/**
* @param FilterInterface[] $filters
*/
private function prepareDataReaderByParams(
?string $page,
?string $previousPage,
?string $pageSize,
?string $sort,
array $filters,
): ReadableDataInterface {
$dataReader = $this->getDataReader();
if (!$dataReader instanceof PaginatorInterface) {
if (
$dataReader instanceof OffsetableDataInterface
&& $dataReader instanceof CountableDataInterface
&& $dataReader instanceof LimitableDataInterface
) {
$dataReader = new OffsetPaginator($dataReader);
} elseif (
$dataReader instanceof FilterableDataInterface
&& $dataReader instanceof SortableDataInterface
&& $dataReader instanceof LimitableDataInterface
) {
if ($dataReader->getSort() !== null) {
$dataReader = new KeysetPaginator($dataReader);
} else {
return $dataReader;
}
} else {
return $dataReader;
}
}
if ($dataReader->isPaginationRequired()) {
if ($pageSize !== null) {
$dataReader = $dataReader->withPageSize((int) $pageSize);
}
if ($page !== null) {
$dataReader = $dataReader->withToken(PageToken::next($page));
} elseif ($previousPage !== null) {
$dataReader = $dataReader->withToken(PageToken::previous($previousPage));
}
}
if (!empty($sort) && $dataReader->isSortable()) {
$sortObject = $dataReader->getSort();
if ($sortObject !== null) {
$order = OrderHelper::stringToArray($sort);
if (!$this->enableMultiSort) {
$order = array_slice($order, 0, 1, true);
}
$this->prepareOrder($order);
$dataReader = $dataReader->withSort($sortObject->withOrder($order));
}
}
if (!empty($filters) && $dataReader->isFilterable()) {
$dataReader = $dataReader->withFilter(new All(...$filters));
}
return $dataReader;
}
/**
* @psalm-param TOrder $order
*/
protected function prepareOrder(array &$order): void
{
}
/**
* Return new instance with the header for the grid.
*
* @param string $value The header of the grid.
*
* {@see headerAttributes}
*/
public function header(string $value): self
{
$new = clone $this;
$new->header = $value;
return $new;
}
/**
* Return new instance with the HTML attributes for the header.
*
* @param array $values Attribute values indexed by attribute names.
*/
public function headerAttributes(array $values): self
{
$new = clone $this;
$new->headerAttributes = $values;
return $new;
}
/**
* Returns a new instance with the id of the grid view, detail view, or list view.
*
* @param string $id The ID of the grid view, detail view, or list view.
*/
public function id(string $id): static
{
$new = clone $this;
$new->containerAttributes['id'] = $id;
return $new;
}
/**
* Returns a new instance with the layout of the grid view, and list view.
*
* @param string $value The template that determines how different sections of the grid view, list view. Should be
* organized.
*
* The following tokens will be replaced with the corresponding section contents:
*
* - `{header}`: The header section.
* - `{toolbar}`: The toolbar section.
*/
public function layout(string $value): static
{
$new = clone $this;
$new->layout = $value;
return $new;
}
public function pagination(string|KeysetPagination|OffsetPagination|null $pagination): static
{
$new = clone $this;
$new->pagination = $pagination;
return $new;
}
/**
* Returns a new instance with the paginator interface of the grid view, detail view, or list view.
*
* @param ReadableDataInterface $dataReader The paginator interface of the grid view, detail view, or list view.
*/
public function dataReader(ReadableDataInterface $dataReader): static
{
$new = clone $this;
$new->dataReader = $dataReader;
return $new;
}
final public function summaryTag(?string $tag): static
{
if ($tag === '') {
throw new InvalidArgumentException('Tag name cannot be empty.');
}
$new = clone $this;
$new->summaryTag = $tag;
return $new;
}
/**
* Returns a new instance with the summary template.
*
* @param string|null $template The HTML content to be displayed as the summary. If you do not want to show
* the summary, you may set it with an empty string or null.
*
* The following tokens will be replaced with the corresponding values:
*
* - `{begin}` — the starting row number (1-based) currently being displayed.
* - `{end}` — the ending row number (1-based) currently being displayed.
* - `{count}` — the number of rows currently being displayed.
* - `{totalCount}` — the total number of rows available.
* - `{currentPage}` — the page number (1-based) current being displayed.
* - `{totalPages}` — the number of pages available.
*/
final public function summaryTemplate(?string $template): static
{
$new = clone $this;
$new->summaryTemplate = $template;
return $new;
}
/**
* Returns a new instance with the HTML attributes for summary wrapper tag.
*
* @param array $values Attribute values indexed by attribute names.
*/
final public function summaryAttributes(array $values): static
{
$new = clone $this;
$new->summaryAttributes = $values;
return $new;
}
/**
* Return new instance with toolbar content.
*
* @param string $value The toolbar content.
*
* @psalm-param array $toolbar
*/
public function toolbar(string $value): self
{
$new = clone $this;
$new->toolbar = $value;
return $new;
}
/**
* Return a new instance with arguments of the route.
*
* @param array $value Arguments of the route.
*
* @psalm-param array<string,scalar|Stringable|null> $value
*/
public function urlArguments(array $value): static
{
$new = clone $this;
$new->urlArguments = $value;
return $new;
}
/**
* Return a new instance with query parameters of the route.
*
* @param array $value The query parameters of the route.
*/
public function urlQueryParameters(array $value): static
{
$new = clone $this;
$new->urlQueryParameters = $value;
return $new;
}
protected function renderEmpty(int $colspan): Td
{
$emptyTextAttributes = $this->emptyTextAttributes;
$emptyTextAttributes['colspan'] = $colspan;
$emptyText = $this->translator->translate(
$this->emptyText ?? 'No results found.',
category: $this->translationCategory
);
return Td::tag()->attributes($emptyTextAttributes)->content($emptyText);
}
public function render(): string
{
[$filters, $filterValidationResult] = $this->makeFilters();
$items = $filters === null ? [] : $this->prepareDataReaderAndGetItems($filters);
$content = trim(
strtr(
$this->layout,
[
'{header}' => $this->renderHeader(),
'{toolbar}' => $this->toolbar,
'{items}' => $this->renderItems($items, $filterValidationResult),
'{summary}' => $this->renderSummary(),
'{pager}' => $this->renderPagination(),
],
)
);
return $this->containerTag === null
? $content
: Html::tag($this->containerTag, "\n" . $content . "\n", $this->containerAttributes)
->encode(false)
->render();
}
protected function getDefaultPageSize(): int
{
$dataReader = $this->getDataReader();
if ($dataReader instanceof PaginatorInterface) {
return $dataReader->getPageSize();
}
return $this->defaultPageSize;
}
private function renderPagination(): string
{
$preparedDataReader = $this->preparedDataReader;
if (!$preparedDataReader instanceof PaginatorInterface || !$preparedDataReader->isPaginationRequired()) {
return '';
}
if (is_string($this->pagination)) {
return $this->pagination;
}
if ($this->pagination === null) {
if ($preparedDataReader instanceof OffsetPaginator) {
$pagination = OffsetPagination::widget();
} elseif ($preparedDataReader instanceof KeysetPaginator) {
$pagination = KeysetPagination::widget();
} else {
return '';
}
} else {
$pagination = $this->pagination;
}
if ($pagination instanceof OffsetPagination && $preparedDataReader instanceof OffsetPaginator) {
$pagination = $pagination->paginator($preparedDataReader);
} elseif ($pagination instanceof KeysetPagination && $preparedDataReader instanceof KeysetPaginator) {
$pagination = $pagination->paginator($preparedDataReader);
} else {
return '';
}
if ($this->urlCreator !== null) {
$pagination = $pagination->urlCreator($this->urlCreator);
}
return $pagination
->defaultPageSize($this->getDefaultPageSize())
->urlConfig($this->urlConfig)
->render();
}
private function renderSummary(): string
{
if (empty($this->summaryTemplate)) {
return '';
}
$dataReader = $this->preparedDataReader;
if (!$dataReader instanceof OffsetPaginator) {
return '';
}
// The total number of rows available
$totalCount = $dataReader->getTotalItems();
if ($totalCount === 0) {
return '';
}
// The page number (1-based) current being displayed
$currentPage = $dataReader->getCurrentPage();
// The starting row number (1-based) currently being displayed
$begin = ($currentPage - 1) * $dataReader->getPageSize() + 1;
// The number of rows currently being displayed
$count = $dataReader->getCurrentPageSize();
// The ending row number (1-based) currently being displayed
$end = $begin + $count - 1;
// The number of pages available
$totalPages = $dataReader->getTotalPages();
$content = $this->translator->translate(
$this->summaryTemplate,
[
'begin' => $begin,
'end' => $end,
'count' => $count,
'totalCount' => $totalCount,
'currentPage' => $currentPage,
'totalPages' => $totalPages,
],
$this->translationCategory,
);
return $this->summaryTag === null
? $content
: Html::tag($this->summaryTag, $content, $this->summaryAttributes)->encode(false)->render();
}
private function renderHeader(): string
{
return match ($this->header) {
'' => '',
default => Div::tag()
->attributes($this->headerAttributes)
->content($this->header)
->encode(false)
->render(),
};
}
/**
* Creates default translator to use if {@see $translator} was not set explicitly in the constructor. Depending on
* "intl" extension availability, either {@see IntlMessageFormatter} or {@see SimpleMessageFormatter} is used as
* formatter.
*
* @return Translator Translator instance used for translations of messages.
*/
private function createDefaultTranslator(): Translator
{
$categorySource = new CategorySource(
$this->translationCategory,
new IdMessageReader(),
extension_loaded('intl') ? new IntlMessageFormatter() : new SimpleMessageFormatter(),
);
$translator = new Translator();
$translator->addCategorySources($categorySource);
return $translator;
}
}