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