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