prepare() once, together with the rest of the query, so no value ever reaches SQL any other way. * * @package Nodebook */ defined( 'ABSPATH' ) || exit; final class Nodebook_Sql { /** A condition that is always true. */ public static function all() { return array( '1=1', array() ); } /** A condition that is never true. */ public static function none() { return array( '1=0', array() ); } /** * Combine conditions with AND (or OR). Empty conditions are skipped. * * @param array[] $parts Conditions. * @param bool $any OR instead of AND. * @return array{0:string,1:array} */ public static function join( array $parts, $any = false ) { $sql = array(); $args = array(); foreach ( $parts as $p ) { if ( ! is_array( $p ) || '' === (string) $p[0] ) { continue; } $sql[] = '(' . $p[0] . ')'; $args = array_merge( $args, (array) $p[1] ); } if ( ! $sql ) { return self::all(); } return array( implode( $any ? ' OR ' : ' AND ', $sql ), $args ); } /** NOT ( condition ). */ public static function not( array $p ) { return array( 'NOT (' . $p[0] . ')', $p[1] ); } /** * Placeholders for a list: "%d,%d,%d". * * @param int $count Number of values (at least 1). * @param string $type %d, %s or %f. */ public static function list_of( $count, $type = '%d' ) { $type = in_array( $type, array( '%d', '%s', '%f' ), true ) ? $type : '%d'; return implode( ',', array_fill( 0, max( 1, (int) $count ), $type ) ); } /** * "column IN (…)" for integer IDs, or a never-true condition when there are none. * * @param string $column Column, written as "alias.column" or "column" (letters, digits, _ only). * @param int[] $ids IDs. */ public static function in_ids( $column, array $ids ) { $ids = array_values( array_unique( array_map( 'intval', $ids ) ) ); if ( ! $ids ) { return self::none(); } $c = self::col( $column ); return array( $c[0] . ' IN (' . self::list_of( count( $ids ) ) . ')', array_merge( $c[1], $ids ) ); } /** * A column as identifier placeholders: "c.email" → array( '%i.%i', array( 'c', 'email' ) ). * * @param string $column Column name, optionally prefixed with a table alias. */ public static function col( $column ) { $parts = array_values( array_filter( explode( '.', preg_replace( '/[^A-Za-z0-9_.]/', '', (string) $column ) ), 'strlen' ) ); if ( 2 === count( $parts ) ) { return array( '%i.%i', $parts ); } return array( '%i', array( $parts ? end( $parts ) : 'id' ) ); } }