ModelColumn.php
116 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Give\Framework\ListTable; |
| 6 | |
| 7 | use Give\Framework\ListTable\Concerns\ListTableData; |
| 8 | use Give\Framework\Support\Contracts\Arrayable; |
| 9 | |
| 10 | /** |
| 11 | * @since 2.24.0 |
| 12 | * |
| 13 | * @template M of Give\Framework\Models\Model |
| 14 | */ |
| 15 | abstract class ModelColumn implements Arrayable |
| 16 | { |
| 17 | |
| 18 | use ListTableData; |
| 19 | |
| 20 | /** |
| 21 | * @var string|array Define the meta key to be used when sorting the query by this column |
| 22 | */ |
| 23 | protected $sortColumn; |
| 24 | |
| 25 | /** |
| 26 | * @var bool Define if the column is visible |
| 27 | */ |
| 28 | protected $visibleColumn; |
| 29 | |
| 30 | /** |
| 31 | * Returns the id for that column. |
| 32 | * |
| 33 | * @since 2.24.0 |
| 34 | */ |
| 35 | abstract public static function getId(): string; |
| 36 | |
| 37 | /** |
| 38 | * Returns the label for that column. |
| 39 | * |
| 40 | * @since 2.24.0 |
| 41 | */ |
| 42 | abstract public function getLabel(): string; |
| 43 | |
| 44 | /** |
| 45 | * Returns the value to be displayed in the specific cell for that column and row. |
| 46 | * |
| 47 | * @since 2.24.0 |
| 48 | * |
| 49 | * @param M $model |
| 50 | * |
| 51 | * @return int|string |
| 52 | */ |
| 53 | abstract public function getCellValue($model); |
| 54 | |
| 55 | /** |
| 56 | * @since 2.24.0 |
| 57 | * |
| 58 | * @return bool |
| 59 | */ |
| 60 | public function isSortable(): bool |
| 61 | { |
| 62 | return null !== $this->sortColumn; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * @since 2.24.0 |
| 67 | * |
| 68 | * @return array |
| 69 | */ |
| 70 | public function getSortColumn(): array |
| 71 | { |
| 72 | if ( ! $this->isSortable() ) { |
| 73 | return []; |
| 74 | } |
| 75 | |
| 76 | return is_array( $this->sortColumn ) ? $this->sortColumn : [$this->sortColumn]; |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * @since 2.24.0 |
| 81 | * |
| 82 | * @param bool $visible |
| 83 | * |
| 84 | * @return void |
| 85 | */ |
| 86 | public function visible(bool $visible) |
| 87 | { |
| 88 | $this->visibleColumn = $visible; |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * @since 2.24.0 |
| 93 | * |
| 94 | * @return bool |
| 95 | */ |
| 96 | public function isVisible(): bool |
| 97 | { |
| 98 | return $this->visibleColumn; |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * @since 2.24.0 |
| 103 | * |
| 104 | * @return array |
| 105 | */ |
| 106 | public function toArray(): array |
| 107 | { |
| 108 | return [ |
| 109 | 'id' => $this->getId(), |
| 110 | 'label' => $this->getLabel(), |
| 111 | 'sortable' => $this->isSortable(), |
| 112 | 'visible' => $this->isVisible(), |
| 113 | ]; |
| 114 | } |
| 115 | } |
| 116 |