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.

89 lines
2.4 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. /**
  56. * @param $key
  57. * @return mixed
  58. * TODO: метод актуален только после вызова assoc
  59. */
  60. public function fetchKey($key)
  61. {
  62. return $this->result_items[$key];
  63. }
  64. /**
  65. * @param $field
  66. * @return mixed
  67. * TODO: метод не актуален после вызова assoc с параметров assoc_as_array = true
  68. */
  69. public function fetchField($field)
  70. {
  71. $item = current($this->result_items);
  72. if ($item) {
  73. return $item->{$field};
  74. }
  75. return false;
  76. }
  77. public function fetch()
  78. {
  79. return current($this->result_items);
  80. }
  81. }