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.

116 lines
2.8 KiB

  1. <?php
  2. class SqlResultProvider
  3. {
  4. /**
  5. * @var array
  6. */
  7. private $result;
  8. /**
  9. * @var array
  10. * @desc my be changed in assoc method
  11. */
  12. private $result_items;
  13. /**
  14. * @var array
  15. */
  16. private $result_items_base;
  17. /**
  18. * @param $result DbStatement
  19. */
  20. public function __construct($result)
  21. {
  22. $this->result = $result;
  23. }
  24. private function defineResultItems()
  25. {
  26. if (is_null($this->result_items_base)) {
  27. $this->result_items_base = $this->result->fetchAll();
  28. $this->result_items = $this->result_items_base;
  29. }
  30. }
  31. /**
  32. * @param $field string
  33. * @param bool $assoc_as_array
  34. * @return $this SqlResultProvider
  35. * @throws ErrorException
  36. */
  37. public function assoc($field, $assoc_as_array = false)
  38. {
  39. $this->defineResultItems();
  40. $result_items_assoc = array();
  41. foreach ($this->result_items_base as $item) {
  42. if (!isset($item->{$field})) {
  43. throw new ErrorException('Undefined field. ' . $field);
  44. }
  45. if ($assoc_as_array) {
  46. if (!isset($result_items_assoc[$item->{$field}])) {
  47. $result_items_assoc[$item->{$field}] = array();
  48. }
  49. $result_items_assoc[$item->{$field}][] = $item;
  50. } else {
  51. if (isset($result_items_assoc[$item->{$field}])) {
  52. throw new ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
  53. }
  54. $result_items_assoc[$item->{$field}] = $item;
  55. }
  56. }
  57. // Ассоциирование внутри каждого элемента массива
  58. if ($assoc_as_array) {
  59. foreach ($result_items_assoc as &$value) {
  60. $value = new SqlResultCollection($value);
  61. }
  62. }
  63. $this->result_items = $result_items_assoc;
  64. return $this;
  65. }
  66. public function getKeys()
  67. {
  68. $this->defineResultItems();
  69. return array_keys($this->result_items);
  70. }
  71. /**
  72. * @return DbStatement[]|SqlResultCollection[]
  73. */
  74. public function fetchAll()
  75. {
  76. $this->defineResultItems();
  77. return $this->result_items;
  78. }
  79. /**
  80. * @param $key
  81. * @return mixed
  82. * метод актуален после вызова assoc
  83. */
  84. public function fetchKey($key)
  85. {
  86. return $this->result_items[$key];
  87. }
  88. /**
  89. * @param $field
  90. * @return mixed
  91. */
  92. public function fetchField($field)
  93. {
  94. return $this->result->fetchField($field);
  95. }
  96. public function fetch($style = Db::FETCH_OBJ)
  97. {
  98. return $this->result->fetch($style);
  99. }
  100. public function affectedRows()
  101. {
  102. return $this->result->affectedRows();
  103. }
  104. }