CompositeExpression.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\DB\QueryBuilder;
  8. use OCP\DB\QueryBuilder\ICompositeExpression;
  9. class CompositeExpression implements ICompositeExpression, \Countable {
  10. public const TYPE_AND = 'AND';
  11. public const TYPE_OR = 'OR';
  12. public function __construct(
  13. private string $type,
  14. private array $parts = []
  15. ) {
  16. }
  17. /**
  18. * Adds multiple parts to composite expression.
  19. *
  20. * @param array $parts
  21. *
  22. * @return \OCP\DB\QueryBuilder\ICompositeExpression
  23. */
  24. public function addMultiple(array $parts = []): ICompositeExpression {
  25. foreach ($parts as $part) {
  26. $this->add($part);
  27. }
  28. return $this;
  29. }
  30. /**
  31. * Adds an expression to composite expression.
  32. *
  33. * @param mixed $part
  34. *
  35. * @return \OCP\DB\QueryBuilder\ICompositeExpression
  36. */
  37. public function add($part): ICompositeExpression {
  38. if ($part === null) {
  39. return $this;
  40. }
  41. if ($part instanceof self && count($part) === 0) {
  42. return $this;
  43. }
  44. $this->parts[] = $part;
  45. return $this;
  46. }
  47. /**
  48. * Retrieves the amount of expressions on composite expression.
  49. *
  50. * @return integer
  51. */
  52. public function count(): int {
  53. return count($this->parts);
  54. }
  55. /**
  56. * Returns the type of this composite expression (AND/OR).
  57. *
  58. * @return string
  59. */
  60. public function getType(): string {
  61. return $this->type;
  62. }
  63. /**
  64. * Retrieves the string representation of this composite expression.
  65. *
  66. * @return string
  67. */
  68. public function __toString(): string {
  69. if ($this->count() === 1) {
  70. return (string)$this->parts[0];
  71. }
  72. return '(' . implode(') ' . $this->type . ' (', $this->parts) . ')';
  73. }
  74. public function getParts(): array {
  75. return $this->parts;
  76. }
  77. }