QuoteHelper.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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\ILiteral;
  9. use OCP\DB\QueryBuilder\IParameter;
  10. use OCP\DB\QueryBuilder\IQueryFunction;
  11. class QuoteHelper {
  12. /**
  13. * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter
  14. * @return array|string
  15. */
  16. public function quoteColumnNames($strings) {
  17. if (!is_array($strings)) {
  18. return $this->quoteColumnName($strings);
  19. }
  20. $return = [];
  21. foreach ($strings as $string) {
  22. $return[] = $this->quoteColumnName($string);
  23. }
  24. return $return;
  25. }
  26. /**
  27. * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter
  28. * @return string
  29. */
  30. public function quoteColumnName($string) {
  31. if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) {
  32. return (string)$string;
  33. }
  34. if ($string === null || $string === 'null' || $string === '*') {
  35. return $string;
  36. }
  37. if (!is_string($string)) {
  38. throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed');
  39. }
  40. $string = str_replace(' AS ', ' as ', $string);
  41. if (substr_count($string, ' as ')) {
  42. return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2)));
  43. }
  44. if (substr_count($string, '.')) {
  45. [$alias, $columnName] = explode('.', $string, 2);
  46. if ($columnName === '*') {
  47. return '`' . $alias . '`.*';
  48. }
  49. return '`' . $alias . '`.`' . $columnName . '`';
  50. }
  51. return '`' . $string . '`';
  52. }
  53. }