Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SearchResultFactory.php
Go to the documentation of this file.
1 <?php
7 
13 use Magento\Framework\Api\Search\SearchResultFactory as BaseSearchResultFactory;
15 
22 {
26  private $hydrator;
27 
31  private $documentFactory;
32 
36  private $searchResultFactory;
37 
41  private $attributeValueFactory;
42 
49  public function __construct(
50  HydratorInterface $hydrator,
51  DocumentFactory $documentFactory,
52  BaseSearchResultFactory $searchResultFactory,
53  AttributeValueFactory $attributeValueFactory
54  ) {
55  $this->hydrator = $hydrator;
56  $this->documentFactory = $documentFactory;
57  $this->searchResultFactory = $searchResultFactory;
58  $this->attributeValueFactory = $attributeValueFactory;
59  }
60 
68  public function create(
69  array $items,
70  $totalCount,
72  $idFieldName
74  $documents = [];
75  foreach ($items as $item) {
76  $itemData = $this->hydrator->extract($item);
77  $itemId = $itemData[$idFieldName];
78  $attributes = $this->createAttributes($idFieldName, $itemData);
79 
80  $document = $this->documentFactory->create();
81  $document->setId($itemId);
82  $document->setCustomAttributes($attributes);
83  $documents[] = $document;
84  }
85 
86  $searchResult = $this->searchResultFactory->create();
87  $searchResult->setItems($documents);
88  $searchResult->setTotalCount($totalCount);
89  $searchResult->setSearchCriteria($searchCriteria);
90  return $searchResult;
91  }
92 
98  private function createAttributes(string $idFieldName, array $itemData): array
99  {
100  $attributes = [];
101 
102  $idFieldNameAttribute = $this->attributeValueFactory->create();
103  $idFieldNameAttribute->setAttributeCode('id_field_name');
104  $idFieldNameAttribute->setValue($idFieldName);
105  $attributes['id_field_name'] = $idFieldNameAttribute;
106 
107  foreach ($itemData as $key => $value) {
108  $attribute = $this->attributeValueFactory->create();
109  $attribute->setAttributeCode($key);
110  if (is_bool($value)) {
111  // for proper work of form and grid (for example for Yes/No properties)
112  $value = (string)(int)$value;
113  }
114  $attribute->setValue($value);
115  $attributes[$key] = $attribute;
116  }
117  return $attributes;
118  }
119 }
create(array $items, $totalCount, SearchCriteriaInterface $searchCriteria, $idFieldName)
$searchCriteria
$value
Definition: gender.phtml:16
$attributes
Definition: matrix.phtml:13
__construct(HydratorInterface $hydrator, DocumentFactory $documentFactory, BaseSearchResultFactory $searchResultFactory, AttributeValueFactory $attributeValueFactory)
$items