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
ContactListRepository.php
81 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Repositories; |
| 4 | |
| 5 | use Exception; |
| 6 | use Hostinger\Reach\Admin\Database\ContactListsTable; |
| 7 | use Hostinger\Reach\Models\ContactList; |
| 8 | use wpdb; |
| 9 | |
| 10 | if ( ! defined( 'ABSPATH' ) ) { |
| 11 | die; |
| 12 | } |
| 13 | |
| 14 | class ContactListRepository extends Repository { |
| 15 | |
| 16 | public function __construct( wpdb $db, ContactListsTable $table ) { |
| 17 | parent::__construct( $db ); |
| 18 | $this->table = $table; |
| 19 | } |
| 20 | |
| 21 | public function all( array $where = array() ): array { |
| 22 | $limit = apply_filters( 'hostinger_reach_contact_lists_limit', 100 ); |
| 23 | $query = $this->build_query( $where, $limit ); |
| 24 | $results = $this->db->get_results( $query, ARRAY_A ); |
| 25 | |
| 26 | $contact_lists = array(); |
| 27 | foreach ( $results as $result ) { |
| 28 | $contact_lists[] = ( new ContactList( $result ) )->to_array(); |
| 29 | } |
| 30 | |
| 31 | return $contact_lists; |
| 32 | } |
| 33 | |
| 34 | public function exists( string $group_name ): bool { |
| 35 | try { |
| 36 | $this->get( $group_name ); |
| 37 | return true; |
| 38 | } catch ( Exception $e ) { |
| 39 | return false; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * @throws Exception |
| 45 | */ |
| 46 | public function get( string $group_name ): array { |
| 47 | $query = $this->db->prepare( 'SELECT * FROM %i WHERE name = %s', $this->table->table_name(), $group_name ); |
| 48 | $results = $this->db->get_results( $query, ARRAY_A ); |
| 49 | if ( ! empty( $results ) ) { |
| 50 | return ( new ContactList( $results[0] ) )->to_array(); |
| 51 | } |
| 52 | |
| 53 | throw new Exception( 'Contact List not found' ); |
| 54 | } |
| 55 | |
| 56 | public function insert( array $fields ): bool { |
| 57 | if ( $this->exists( $fields['name'] ) ) { |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | return $this->db->insert( $this->table->table_name(), $fields ); |
| 62 | } |
| 63 | |
| 64 | public function update( array $fields ): bool { |
| 65 | if ( ! isset( $fields['id'] ) ) { |
| 66 | return false; |
| 67 | } |
| 68 | |
| 69 | $data = array_diff_key( $fields, array_flip( array( 'id' ) ) ); |
| 70 | if ( empty( $data ) ) { |
| 71 | return false; |
| 72 | } |
| 73 | |
| 74 | return $this->db->update( |
| 75 | $this->table->table_name(), |
| 76 | $data, |
| 77 | array( 'id' => $fields['id'] ) |
| 78 | ); |
| 79 | } |
| 80 | } |
| 81 |