Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Queryable
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 3
42
0.00% covered (danger)
0.00%
0 / 1
 query
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 table
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 bulkInsert
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace NewfoldLabs\WP\Module\Data\EventQueue;
4
5trait Queryable {
6
7    /**
8     * Get a new query instance
9     *
10     * @return \WP_Forge\QueryBuilder\Query
11     */
12    protected function query() {
13        return $this->container->get( 'query' );
14    }
15
16    /**
17     * Get the table name
18     *
19     * @return string
20     */
21    protected function table() {
22        return $this->container->get( 'table' );
23    }
24
25    /**
26     * Bulk inserts records into a table using WPDB.  All rows must contain the same keys.
27     * Returns number of affected (inserted) rows.
28     *
29     * @param  string          $table
30     * @param  non-empty-array $rows
31     *
32     * @return bool|int
33     */
34    protected function bulkInsert( string $table, array $rows ) {
35        global $wpdb;
36
37        // Extract column list from first row of data
38        $columns = array_keys( $rows[0] );
39        asort( $columns );
40        $columnList = '`' . implode( '`, `', $columns ) . '`';
41
42        // Start building SQL, initialise data and placeholder arrays
43        $sql          = "INSERT INTO `$table` ($columnList) VALUES\n";
44        $placeholders = array();
45        $data         = array();
46
47        // Build placeholders for each row, and add values to data array
48        foreach ( $rows as $row ) {
49            ksort( $row );
50            $rowPlaceholders = array();
51
52            foreach ( $row as $key => $value ) {
53                $data[]            = $value;
54                $rowPlaceholders[] = is_numeric( $value ) ? '%d' : '%s';
55            }
56
57            $placeholders[] = '(' . implode( ', ', $rowPlaceholders ) . ')';
58        }
59
60        // Stitch all rows together
61        $sql .= implode( ",\n", $placeholders );
62
63        // Run the query.  Returns number of affected rows.
64        return $wpdb->query( $wpdb->prepare( $sql, $data ) );
65    }
66}