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.

72 lines
2.3 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, $field_assoc_in_array = null)
  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. // $field_assoc_in_array - ассоциирование произовдится по этому полю (вернет ошибку, если этого поля нет в результатх выборки)
  40. if ($assoc_as_array && $field_assoc_in_array) {
  41. foreach ($result_items_assoc as &$value) {
  42. $sql_result_provider = new SqlResultProvider($value);
  43. $value = $sql_result_provider->assoc($field_assoc_in_array)->fetchAll();
  44. }
  45. }
  46. $this->result_items = $result_items_assoc;
  47. return $this;
  48. }
  49. public function getKeys()
  50. {
  51. return array_keys($this->result_items);
  52. }
  53. public function fetchAll()
  54. {
  55. return $this->result_items;
  56. }
  57. public function fetchKey($key)
  58. {
  59. return $this->result_items[$key];
  60. }
  61. public function fetch()
  62. {
  63. return current($this->result_items);
  64. }
  65. }