CompositeExpression.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace Doctrine\DBAL\Query\Expression;
  3. use Countable;
  4. use function count;
  5. use function implode;
  6. /**
  7. * Composite expression is responsible to build a group of similar expression.
  8. */
  9. class CompositeExpression implements Countable
  10. {
  11. /**
  12. * Constant that represents an AND composite expression.
  13. */
  14. public const TYPE_AND = 'AND';
  15. /**
  16. * Constant that represents an OR composite expression.
  17. */
  18. public const TYPE_OR = 'OR';
  19. /**
  20. * The instance type of composite expression.
  21. *
  22. * @var string
  23. */
  24. private $type;
  25. /**
  26. * Each expression part of the composite expression.
  27. *
  28. * @var self[]|string[]
  29. */
  30. private $parts = [];
  31. /**
  32. * @param string $type Instance type of composite expression.
  33. * @param self[]|string[] $parts Composition of expressions to be joined on composite expression.
  34. */
  35. public function __construct($type, array $parts = [])
  36. {
  37. $this->type = $type;
  38. $this->addMultiple($parts);
  39. }
  40. /**
  41. * Adds multiple parts to composite expression.
  42. *
  43. * @param self[]|string[] $parts
  44. *
  45. * @return \Doctrine\DBAL\Query\Expression\CompositeExpression
  46. */
  47. public function addMultiple(array $parts = [])
  48. {
  49. foreach ($parts as $part) {
  50. $this->add($part);
  51. }
  52. return $this;
  53. }
  54. /**
  55. * Adds an expression to composite expression.
  56. *
  57. * @param mixed $part
  58. *
  59. * @return \Doctrine\DBAL\Query\Expression\CompositeExpression
  60. */
  61. public function add($part)
  62. {
  63. if (empty($part)) {
  64. return $this;
  65. }
  66. if ($part instanceof self && count($part) === 0) {
  67. return $this;
  68. }
  69. $this->parts[] = $part;
  70. return $this;
  71. }
  72. /**
  73. * Retrieves the amount of expressions on composite expression.
  74. *
  75. * @return int
  76. */
  77. public function count()
  78. {
  79. return count($this->parts);
  80. }
  81. /**
  82. * Retrieves the string representation of this composite expression.
  83. *
  84. * @return string
  85. */
  86. public function __toString()
  87. {
  88. if ($this->count() === 1) {
  89. return (string) $this->parts[0];
  90. }
  91. return '(' . implode(') ' . $this->type . ' (', $this->parts) . ')';
  92. }
  93. /**
  94. * Returns the type of this composite expression (AND/OR).
  95. *
  96. * @return string
  97. */
  98. public function getType()
  99. {
  100. return $this->type;
  101. }
  102. }