Builder.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Elasticsearch\Model\Adapter\Document;
  7. /**
  8. * @api
  9. * @since 100.1.0
  10. */
  11. class Builder
  12. {
  13. /**
  14. * @var array
  15. */
  16. private $fields = [];
  17. /**
  18. * @return array
  19. * @since 100.1.0
  20. */
  21. public function build()
  22. {
  23. $document = [];
  24. foreach ($this->fields as $field => $value) {
  25. $document = $this->addFieldToDocument($document, $field, $value);
  26. }
  27. $this->clear();
  28. return $document;
  29. }
  30. /**
  31. * @return void
  32. */
  33. private function clear()
  34. {
  35. $this->fields = [];
  36. }
  37. /**
  38. * @param array $document
  39. * @param string $field
  40. * @param string|int|float $value
  41. * @return array
  42. */
  43. private function addFieldToDocument($document, $field, $value)
  44. {
  45. if (is_array($value)) {
  46. if (count($value) == 0) {
  47. $document = array_merge($document, [$field => $value]);
  48. } else {
  49. $fields = [];
  50. foreach ($value as $key => $val) {
  51. $fields[$field][$key] = $val;
  52. }
  53. $document = array_merge($document, $fields);
  54. }
  55. } else {
  56. $field = [$field => $value];
  57. $document = array_merge($document, $field);
  58. }
  59. return $document;
  60. }
  61. /**
  62. * @param string $field
  63. * @param string|array|int|float $value
  64. * @return $this
  65. * @since 100.1.0
  66. */
  67. public function addField($field, $value)
  68. {
  69. $this->fields[$field] = $value;
  70. return $this;
  71. }
  72. /**
  73. * @param array $fields
  74. * @return $this
  75. * @since 100.1.0
  76. */
  77. public function addFields(array $fields)
  78. {
  79. $this->fields = array_merge($this->fields, $fields);
  80. return $this;
  81. }
  82. }