MediaWiki master
ExpressionGroup.php
Go to the documentation of this file.
1<?php
2
3namespace Wikimedia\Rdbms;
4
5use InvalidArgumentException;
7
8// Very long type annotations :(
9// phpcs:disable Generic.Files.LineLength
10
16abstract class ExpressionGroup implements IExpression {
20 protected array $children = [];
21
26 public function __construct( IExpression ...$children ) {
27 $this->children = $children;
28 }
29
30 final protected function add( IExpression $expression ) {
31 $this->children[] = $expression;
32 }
33
34 abstract protected function getType(): string;
35
42 public static function newFromArray( array $conds ) {
43 if ( !$conds ) {
44 throw new InvalidArgumentException( "The array of conditions can't be empty." );
45 }
46 $exprs = [];
47 foreach ( $conds as $field => $cond ) {
48 if ( is_numeric( $field ) ) {
49 if ( !$cond instanceof IExpression ) {
50 throw new InvalidArgumentException( __METHOD__ . ": Only IExpression are allowed with numeric key." );
51 }
52 $exprs[] = $cond;
53 } else {
54 if ( $cond instanceof IExpression ) {
55 throw new InvalidArgumentException( __METHOD__ . ": unexpected key $field for IExpression value" );
56 }
57 $exprs[] = new Expression( $field, '=', $cond );
58 }
59 }
60 // @phan-suppress-next-line PhanTypeInstantiateAbstractStatic
61 return new static( ...$exprs );
62 }
63
69 final public function toSql( DbQuoter $dbQuoter ): string {
70 if ( !$this->children ) {
71 throw new InvalidArgumentException( "The array of values can't be empty." );
72 }
73 $sqls = array_map( static fn ( $value ) => $value->toSql( $dbQuoter ), $this->children );
74 return '(' . implode( ' ' . $this->getType() . ' ', $sqls ) . ')';
75 }
76
77 final public function toGeneralizedSql(): string {
78 if ( !$this->children ) {
79 throw new InvalidArgumentException( "The array of values can't be empty." );
80 }
81 $sqls = array_map( static fn ( $value ) => $value->toGeneralizedSql(), $this->children );
82 return '(' . implode( ' ' . $this->getType() . ' ', $sqls ) . ')';
83 }
84}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
A composite node representing a group of expressions.
add(IExpression $expression)
static newFromArray(array $conds)
__construct(IExpression ... $children)
toGeneralizedSql()
Return SQL for aggregated logging.
A composite leaf representing an expression.