Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Collection.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
11 use Magento\Bundle\Model\ResourceModel\Selection\CollectionFactory;
14 
19 {
23  private $linkCollectionFactory;
24 
28  private $enumLookup;
29 
33  private $optionIds = [];
34 
38  private $parentIds = [];
39 
43  private $links = [];
44 
49  public function __construct(CollectionFactory $linkCollectionFactory, EnumLookup $enumLookup)
50  {
51  $this->linkCollectionFactory = $linkCollectionFactory;
52  $this->enumLookup = $enumLookup;
53  }
54 
62  public function addIdFilters(int $optionId, int $parentId) : void
63  {
64  if (!in_array($optionId, $this->optionIds)) {
65  $this->optionIds[] = $optionId;
66  }
67  if (!in_array($parentId, $this->parentIds)) {
68  $this->parentIds[] = $parentId;
69  }
70  }
71 
78  public function getLinksForOptionId(int $optionId) : array
79  {
80  $linksList = $this->fetch();
81 
82  if (!isset($linksList[$optionId])) {
83  return [];
84  }
85 
86  return $linksList[$optionId];
87  }
88 
94  private function fetch() : array
95  {
96  if (empty($this->optionIds) || empty($this->parentIds) || !empty($this->links)) {
97  return $this->links;
98  }
99 
101  $linkCollection = $this->linkCollectionFactory->create();
102  $linkCollection->setOptionIdsFilter($this->optionIds);
103  $field = 'parent_product_id';
104  foreach ($linkCollection->getSelect()->getPart('from') as $tableAlias => $data) {
105  if ($data['tableName'] == $linkCollection->getTable('catalog_product_bundle_selection')) {
106  $field = $tableAlias . '.' . $field;
107  }
108  }
109 
110  $linkCollection->getSelect()
111  ->where($field . ' IN (?)', $this->parentIds);
112 
114  foreach ($linkCollection as $link) {
115  $data = $link->getData();
116  $formattedLink = [
117  'price' => $link->getSelectionPriceValue(),
118  'position' => $link->getPosition(),
119  'id' => $link->getSelectionId(),
120  'qty' => (int)$link->getSelectionQty(),
121  'is_default' => (bool)$link->getIsDefault(),
122  'price_type' => $this->enumLookup->getEnumValueFromField(
123  'PriceTypeEnum',
124  (string)$link->getSelectionPriceType()
125  ) ?: 'DYNAMIC',
126  'can_change_quantity' => $link->getSelectionCanChangeQty(),
127  ];
128  $data = array_replace($data, $formattedLink);
129  if (!isset($this->links[$link->getOptionId()])) {
130  $this->links[$link->getOptionId()] = [];
131  }
132  $this->links[$link->getOptionId()][] = $data;
133  }
134 
135  return $this->links;
136  }
137 }