CartRepository.php
7 months ago
ContactListRepository.php
8 months ago
FormRepository.php
8 months ago
Repository.php
8 months ago
RepositoryInterface.php
8 months ago
Repository.php
50 lines
| 1 | <?php |
| 2 | namespace Hostinger\Reach\Repositories; |
| 3 | |
| 4 | use Hostinger\Reach\Admin\Database\DatabaseInterface; |
| 5 | use wpdb; |
| 6 | |
| 7 | if ( ! DEFINED( 'ABSPATH' ) ) { |
| 8 | exit; |
| 9 | } |
| 10 | |
| 11 | abstract class Repository implements RepositoryInterface { |
| 12 | protected DatabaseInterface $table; |
| 13 | protected wpdb $db; |
| 14 | |
| 15 | public function __construct( wpdb $db ) { |
| 16 | $this->db = $db; |
| 17 | } |
| 18 | |
| 19 | abstract public function all( array $where = array() ): array; |
| 20 | abstract public function exists( string $id ): bool; |
| 21 | abstract public function get( string $id ): array; |
| 22 | abstract public function insert( array $fields ): bool; |
| 23 | abstract public function update( array $fields ): bool; |
| 24 | protected function build_query( array $where = array(), int $limit = 100, int $offset = 0 ): string { |
| 25 | $sql = 'SELECT * FROM %i'; |
| 26 | $params = array( $this->table->table_name() ); |
| 27 | |
| 28 | if ( ! empty( $where ) ) { |
| 29 | $where_conditions = array(); |
| 30 | foreach ( $where as $column => $value ) { |
| 31 | if ( is_array( $value ) && isset( $value['operator'], $value['value'] ) ) { |
| 32 | $operator = $value['operator']; |
| 33 | $where_conditions[] = $column . ' ' . $operator . ' %s'; |
| 34 | $params[] = $value['value']; |
| 35 | } else { |
| 36 | $where_conditions[] = $column . ' = %s'; |
| 37 | $params[] = $value; |
| 38 | } |
| 39 | } |
| 40 | $sql .= ' WHERE ' . implode( ' AND ', $where_conditions ); |
| 41 | } |
| 42 | |
| 43 | $sql .= ' LIMIT ' . $limit; |
| 44 | if ( $offset ) { |
| 45 | $sql .= ' OFFSET ' . $offset; |
| 46 | } |
| 47 | return $this->db->prepare( $sql, ...$params ); |
| 48 | } |
| 49 | } |
| 50 |