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.

114 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. return array_keys($this->result);
  69. }
  70. /**
  71. * @return DbStatement[]|SqlResultCollection[]
  72. */
  73. public function fetchAll()
  74. {
  75. $this->defineResultItems();
  76. return $this->result_items;
  77. }
  78. /**
  79. * @param $key
  80. * @return mixed
  81. * метод актуален после вызова assoc
  82. */
  83. public function fetchKey($key)
  84. {
  85. return $this->result_items[$key];
  86. }
  87. /**
  88. * @param $field
  89. * @return mixed
  90. */
  91. public function fetchField($field)
  92. {
  93. return $this->result->fetchField($field);
  94. }
  95. public function fetch($style = Db::FETCH_OBJ)
  96. {
  97. return $this->result->fetch($style);
  98. }
  99. public function affectedRows()
  100. {
  101. return $this->result->affectedRows();
  102. }
  103. }