You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

QuoteHelper.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. *
  8. * @license AGPL-3.0
  9. *
  10. * This code is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License, version 3,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License, version 3,
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>
  21. *
  22. */
  23. namespace OC\DB\QueryBuilder;
  24. use OCP\DB\QueryBuilder\ILiteral;
  25. use OCP\DB\QueryBuilder\IParameter;
  26. use OCP\DB\QueryBuilder\IQueryFunction;
  27. class QuoteHelper {
  28. /**
  29. * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter
  30. * @return array|string
  31. */
  32. public function quoteColumnNames($strings) {
  33. if (!is_array($strings)) {
  34. return $this->quoteColumnName($strings);
  35. }
  36. $return = [];
  37. foreach ($strings as $string) {
  38. $return[] = $this->quoteColumnName($string);
  39. }
  40. return $return;
  41. }
  42. /**
  43. * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter
  44. * @return string
  45. */
  46. public function quoteColumnName($string) {
  47. if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) {
  48. return (string) $string;
  49. }
  50. if ($string === null || $string === 'null' || $string === '*') {
  51. return $string;
  52. }
  53. if (!is_string($string)) {
  54. throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed');
  55. }
  56. $string = str_replace(' AS ', ' as ', $string);
  57. if (substr_count($string, ' as ')) {
  58. return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2)));
  59. }
  60. if (substr_count($string, '.')) {
  61. [$alias, $columnName] = explode('.', $string, 2);
  62. if ($columnName === '*') {
  63. return '`' . $alias . '`.*';
  64. }
  65. return '`' . $alias . '`.`' . $columnName . '`';
  66. }
  67. return '`' . $string . '`';
  68. }
  69. }