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.

75 lines
2.0 KiB

  1. <?php
  2. class SqlResultProvider
  3. {
  4. /**
  5. * @var array
  6. */
  7. private $result_items;
  8. private $result_items_base;
  9. /**
  10. * @param $result_items array
  11. */
  12. public function __construct($result_items)
  13. {
  14. $this->result_items = $result_items;
  15. }
  16. public function assoc($field, $assoc_as_array = false)
  17. {
  18. if (is_null($this->result_items_base)) {
  19. $this->result_items_base = $this->result_items;
  20. }
  21. $result_items_assoc = array();
  22. foreach ($this->result_items_base as $item) {
  23. if (!isset($item->{$field})) {
  24. throw new ErrorException('Undefined field. ' . $field);
  25. }
  26. if ($assoc_as_array) {
  27. if (!isset($result_items_assoc[$item->{$field}])) {
  28. $result_items_assoc[$item->{$field}] = array();
  29. }
  30. $result_items_assoc[$item->{$field}][] = $item;
  31. } else {
  32. if (isset($result_items_assoc[$item->{$field}])) {
  33. throw new ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
  34. }
  35. $result_items_assoc[$item->{$field}] = $item;
  36. }
  37. }
  38. // Ассоциирование внутри каждого элемента массива
  39. if ($assoc_as_array) {
  40. foreach ($result_items_assoc as &$value) {
  41. $value = new SqlResultProvider($value);
  42. }
  43. }
  44. $this->result_items = $result_items_assoc;
  45. return $this;
  46. }
  47. public function getKeys()
  48. {
  49. return array_keys($this->result_items);
  50. }
  51. public function fetchAll()
  52. {
  53. return $this->result_items;
  54. }
  55. public function fetchKey($key)
  56. {
  57. return $this->result_items[$key];
  58. }
  59. public function fetchField($field)
  60. {
  61. return current($this->result_items)->{$field};
  62. }
  63. public function fetch()
  64. {
  65. return current($this->result_items);
  66. }
  67. }