Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
BasketBuilder.php
1<?php
2
4
8
9class BasketBuilder implements \IteratorAggregate, \Countable
10{
12 private $items = [];
13
14 public function __construct()
15 {
16 }
17
18 public function add(BasketItem ...$items): self
19 {
20 foreach ($items as $item)
21 {
22 $this->setItem($item);
23 }
24
25 return $this;
26 }
27
28 public function createItem(): BasketItem
29 {
30 return new BasketItem();
31 }
32
33 public function setItem(BasketItem $item): self
34 {
35 $this->items[$item->getId()] = $item;
36
37 return $this;
38 }
39
40 public function loadItemsBySkuIds(array $ids): self
41 {
42 foreach ($ids as $id)
43 {
44 $id = (int)$id;
45 if ($id > 0)
46 {
47 $item = $this->loadItemBySkuId($id);
48 if ($item)
49 {
50 $this->setItem($item);
51 $item->setSort($this->count() * 100);
52 }
53 }
54 }
55
56 return $this;
57 }
58
59 public function loadItemBySkuId(int $id): ?BasketItem
60 {
61 $repositoryFacade = ServiceContainer::getRepositoryFacade();
62 if ($repositoryFacade)
63 {
64 $variation = $repositoryFacade->loadVariation($id);
65 }
66
67 if ($variation === null)
68 {
69 return null;
70 }
71
72 $item = $this->createItem();
73
74 $item->setSku($variation);
75
76 return $item;
77 }
78
79 public function getItemById(string $uniqId): ?BasketItem
80 {
81 return $this->items[$uniqId] ?? null;
82 }
83
84 public function getItemBySkuId(int $id): ?BasketItem
85 {
86 foreach ($this->items as $item)
87 {
88 if ($item->getSkuId() === $id)
89 {
90 return $item;
91 }
92 }
93
94 return null;
95 }
96
97 public function getIterator(): \ArrayIterator
98 {
99 return new \ArrayIterator(array_values($this->items));
100 }
101
102 public function clear(): self
103 {
104 $this->items = [];
105
106 return $this;
107 }
108
109 public function count(): int
110 {
111 return count($this->getIterator());
112 }
113
114 public function getJsObject(): string
115 {
116 return \CUtil::PhpToJSObject($this->getFormattedItems());
117 }
118
119 public function getFormattedItems(): array
120 {
121 $result = [];
122 foreach ($this->getIterator() as $item)
123 {
124 $result[] = $item->getResult();
125 }
126
127 return $result;
128 }
129}