ArrayResult.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\DB;
  8. use OCP\DB\IResult;
  9. use PDO;
  10. /**
  11. * Wrap an array or rows into a result interface
  12. */
  13. class ArrayResult implements IResult {
  14. protected int $count;
  15. public function __construct(
  16. protected array $rows,
  17. ) {
  18. $this->count = count($this->rows);
  19. }
  20. public function closeCursor(): bool {
  21. // noop
  22. return true;
  23. }
  24. public function fetch(int $fetchMode = PDO::FETCH_ASSOC) {
  25. $row = array_shift($this->rows);
  26. if (!$row) {
  27. return false;
  28. }
  29. return match ($fetchMode) {
  30. PDO::FETCH_ASSOC => $row,
  31. PDO::FETCH_NUM => array_values($row),
  32. PDO::FETCH_COLUMN => current($row),
  33. default => throw new \InvalidArgumentException('Fetch mode not supported for array result'),
  34. };
  35. }
  36. public function fetchAll(int $fetchMode = PDO::FETCH_ASSOC): array {
  37. return match ($fetchMode) {
  38. PDO::FETCH_ASSOC => $this->rows,
  39. PDO::FETCH_NUM => array_map(function ($row) {
  40. return array_values($row);
  41. }, $this->rows),
  42. PDO::FETCH_COLUMN => array_map(function ($row) {
  43. return current($row);
  44. }, $this->rows),
  45. default => throw new \InvalidArgumentException('Fetch mode not supported for array result'),
  46. };
  47. }
  48. public function fetchColumn() {
  49. return $this->fetchOne();
  50. }
  51. public function fetchOne() {
  52. $row = $this->fetch();
  53. if ($row) {
  54. return current($row);
  55. } else {
  56. return false;
  57. }
  58. }
  59. public function rowCount(): int {
  60. return $this->count;
  61. }
  62. }