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 namespace Magento\Framework\Data;
7 
10 
19 class Collection implements \IteratorAggregate, \Countable, ArrayInterface, CollectionDataSourceInterface
20 {
21  const SORT_ORDER_ASC = 'ASC';
22 
23  const SORT_ORDER_DESC = 'DESC';
24 
30  protected $_items = [];
31 
37  protected $_itemObjectClass = \Magento\Framework\DataObject::class;
38 
44  protected $_orders = [];
45 
51  protected $_filters = [];
52 
58  protected $_isFiltersRendered = false;
59 
65  protected $_curPage = 1;
66 
74  protected $_pageSize = false;
75 
81  protected $_totalRecords;
82 
89 
95  protected $_flags = [];
96 
100  protected $_entityFactory;
101 
105  public function __construct(EntityFactoryInterface $entityFactory)
106  {
107  $this->_entityFactory = $entityFactory;
108  }
109 
118  public function addFilter($field, $value, $type = 'and')
119  {
120  $filter = new \Magento\Framework\DataObject();
121  // implements ArrayAccess
122  $filter['field'] = $field;
123  $filter['value'] = $value;
124  $filter['type'] = strtolower($type);
125 
126  $this->_filters[] = $filter;
127  $this->_isFiltersRendered = false;
128  return $this;
129  }
130 
170  public function addFieldToFilter($field, $condition)
171  {
172  throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Not implemented'));
173  }
174 
187  public function getFilter($field)
188  {
189  if (is_array($field)) {
190  // empty array: get all filters
191  if (empty($field)) {
192  return $this->_filters;
193  }
194  // non-empty array: collect all filters that match specified field names
195  $result = [];
196  foreach ($this->_filters as $filter) {
197  if (in_array($filter['field'], $field)) {
198  $result[] = $filter;
199  }
200  }
201  return $result;
202  }
203 
204  // get a first filter by specified name
205  foreach ($this->_filters as $filter) {
206  if ($filter['field'] === $field) {
207  return $filter;
208  }
209  }
210  }
211 
217  public function isLoaded()
218  {
220  }
221 
228  protected function _setIsLoaded($flag = true)
229  {
230  $this->_isCollectionLoaded = $flag;
231  return $this;
232  }
233 
240  public function getCurPage($displacement = 0)
241  {
242  if ($this->_curPage + $displacement < 1) {
243  return 1;
244  } elseif ($this->_curPage + $displacement > $this->getLastPageNumber()) {
245  return $this->getLastPageNumber();
246  } else {
247  return $this->_curPage + $displacement;
248  }
249  }
250 
256  public function getLastPageNumber()
257  {
258  $collectionSize = (int)$this->getSize();
259  if (0 === $collectionSize) {
260  return 1;
261  } elseif ($this->_pageSize) {
262  return ceil($collectionSize / $this->_pageSize);
263  } else {
264  return 1;
265  }
266  }
267 
273  public function getPageSize()
274  {
275  return $this->_pageSize;
276  }
277 
283  public function getSize()
284  {
285  $this->load();
286  if ($this->_totalRecords === null) {
287  $this->_totalRecords = count($this->getItems());
288  }
289  return intval($this->_totalRecords);
290  }
291 
297  public function getFirstItem()
298  {
299  $this->load();
300 
301  if (count($this->_items)) {
302  reset($this->_items);
303  return current($this->_items);
304  }
305 
306  return $this->_entityFactory->create($this->_itemObjectClass);
307  }
308 
314  public function getLastItem()
315  {
316  $this->load();
317 
318  if (count($this->_items)) {
319  return end($this->_items);
320  }
321 
322  return $this->_entityFactory->create($this->_itemObjectClass);
323  }
324 
330  public function getItems()
331  {
332  $this->load();
333  return $this->_items;
334  }
335 
342  public function getColumnValues($colName)
343  {
344  $this->load();
345 
346  $col = [];
347  foreach ($this->getItems() as $item) {
348  $col[] = $item->getData($colName);
349  }
350  return $col;
351  }
352 
360  public function getItemsByColumnValue($column, $value)
361  {
362  $this->load();
363 
364  $res = [];
365  foreach ($this as $item) {
366  if ($item->getData($column) == $value) {
367  $res[] = $item;
368  }
369  }
370  return $res;
371  }
372 
380  public function getItemByColumnValue($column, $value)
381  {
382  $this->load();
383 
384  foreach ($this as $item) {
385  if ($item->getData($column) == $value) {
386  return $item;
387  }
388  }
389  return null;
390  }
391 
399  public function addItem(\Magento\Framework\DataObject $item)
400  {
401  $itemId = $this->_getItemId($item);
402 
403  if ($itemId !== null) {
404  if (isset($this->_items[$itemId])) {
405  throw new \Exception(
406  'Item (' . get_class($item) . ') with the same ID "' . $item->getId() . '" already exists.'
407  );
408  }
409  $this->_items[$itemId] = $item;
410  } else {
411  $this->_addItem($item);
412  }
413  return $this;
414  }
415 
422  protected function _addItem($item)
423  {
424  $this->_items[] = $item;
425  return $this;
426  }
427 
434  protected function _getItemId(\Magento\Framework\DataObject $item)
435  {
436  return $item->getId();
437  }
438 
444  public function getAllIds()
445  {
446  $ids = [];
447  foreach ($this->getItems() as $item) {
448  $ids[] = $this->_getItemId($item);
449  }
450  return $ids;
451  }
452 
459  public function removeItemByKey($key)
460  {
461  if (isset($this->_items[$key])) {
462  unset($this->_items[$key]);
463  }
464  return $this;
465  }
466 
472  public function removeAllItems()
473  {
474  $this->_items = [];
475  return $this;
476  }
477 
483  public function clear()
484  {
485  $this->_setIsLoaded(false);
486  $this->_items = [];
487  return $this;
488  }
489 
500  public function walk($callback, array $args = [])
501  {
502  $results = [];
503  $useItemCallback = is_string($callback) && strpos($callback, '::') === false;
504  foreach ($this->getItems() as $id => $item) {
505  $params = $args;
506  if ($useItemCallback) {
507  $cb = [$item, $callback];
508  } else {
509  $cb = $callback;
510  array_unshift($params, $item);
511  }
512  $results[$id] = call_user_func_array($cb, $params);
513  }
514  return $results;
515  }
516 
524  public function each($objMethod, $args = [])
525  {
526  if ($objMethod instanceof \Closure) {
527  foreach ($this->getItems() as $item) {
528  $objMethod($item, ...$args);
529  }
530  } elseif (is_array($objMethod)) {
531  foreach ($this->getItems() as $item) {
532  call_user_func($objMethod, $item, ...$args);
533  }
534  } else {
535  foreach ($this->getItems() as $item) {
536  $item->$objMethod(...$args);
537  }
538  }
539  }
540 
548  public function setDataToAll($key, $value = null)
549  {
550  if (is_array($key)) {
551  foreach ($key as $k => $v) {
552  $this->setDataToAll($k, $v);
553  }
554  return $this;
555  }
556  foreach ($this->getItems() as $item) {
557  $item->setData($key, $value);
558  }
559  return $this;
560  }
561 
568  public function setCurPage($page)
569  {
570  $this->_curPage = $page;
571  return $this;
572  }
573 
580  public function setPageSize($size)
581  {
582  $this->_pageSize = $size;
583  return $this;
584  }
585 
593  public function setOrder($field, $direction = self::SORT_ORDER_DESC)
594  {
595  $this->_orders[$field] = $direction;
596  return $this;
597  }
598 
607  {
608  if (!is_a($className, \Magento\Framework\DataObject::class, true)) {
609  throw new \InvalidArgumentException($className . ' does not extend \Magento\Framework\DataObject');
610  }
611  $this->_itemObjectClass = $className;
612  return $this;
613  }
614 
620  public function getNewEmptyItem()
621  {
622  return $this->_entityFactory->create($this->_itemObjectClass);
623  }
624 
630  protected function _renderFilters()
631  {
632  return $this;
633  }
634 
640  protected function _renderOrders()
641  {
642  return $this;
643  }
644 
650  protected function _renderLimit()
651  {
652  return $this;
653  }
654 
662  public function distinct($flag)
663  {
664  return $this;
665  }
666 
675  public function loadData($printQuery = false, $logQuery = false)
676  {
677  return $this;
678  }
679 
687  public function load($printQuery = false, $logQuery = false)
688  {
689  return $this->loadData($printQuery, $logQuery);
690  }
691 
699  public function loadWithFilter($printQuery = false, $logQuery = false)
700  {
701  return $this->loadData($printQuery, $logQuery);
702  }
703 
709  public function toXml()
710  {
711  $xml = '<?xml version="1.0" encoding="UTF-8"?>
712  <collection>
713  <totalRecords>' .
714  $this->_totalRecords .
715  '</totalRecords>
716  <items>';
717 
718  foreach ($this as $item) {
719  $xml .= $item->toXml();
720  }
721  $xml .= '</items>
722  </collection>';
723  return $xml;
724  }
725 
732  public function toArray($arrRequiredFields = [])
733  {
734  $arrItems = [];
735  $arrItems['totalRecords'] = $this->getSize();
736 
737  $arrItems['items'] = [];
738  foreach ($this as $item) {
739  $arrItems['items'][] = $item->toArray($arrRequiredFields);
740  }
741  return $arrItems;
742  }
743 
760  protected function _toOptionArray($valueField = 'id', $labelField = 'name', $additional = [])
761  {
762  $res = [];
763  $additional['value'] = $valueField;
764  $additional['label'] = $labelField;
765 
766  foreach ($this as $item) {
767  foreach ($additional as $code => $field) {
768  $data[$code] = $item->getData($field);
769  }
770  $res[] = $data;
771  }
772  return $res;
773  }
774 
778  public function toOptionArray()
779  {
780  return $this->_toOptionArray();
781  }
782 
786  public function toOptionHash()
787  {
788  return $this->_toOptionHash();
789  }
790 
801  protected function _toOptionHash($valueField = 'id', $labelField = 'name')
802  {
803  $res = [];
804  foreach ($this as $item) {
805  $res[$item->getData($valueField)] = $item->getData($labelField);
806  }
807  return $res;
808  }
809 
816  public function getItemById($idValue)
817  {
818  $this->load();
819  if (isset($this->_items[$idValue])) {
820  return $this->_items[$idValue];
821  }
822  return null;
823  }
824 
830  public function getIterator()
831  {
832  $this->load();
833  return new \ArrayIterator($this->_items);
834  }
835 
841  public function count()
842  {
843  $this->load();
844  return count($this->_items);
845  }
846 
853  public function getFlag($flag)
854  {
855  return $this->_flags[$flag] ?? null;
856  }
857 
865  public function setFlag($flag, $value = null)
866  {
867  $this->_flags[$flag] = $value;
868  return $this;
869  }
870 
877  public function hasFlag($flag)
878  {
879  return array_key_exists($flag, $this->_flags);
880  }
881 
886  public function __sleep()
887  {
888  $properties = array_keys(get_object_vars($this));
889  $properties = array_diff(
890  $properties,
891  [
892  '_entityFactory',
893  ]
894  );
895  return $properties;
896  }
897 
904  public function __wakeup()
905  {
907  $this->_entityFactory = $objectManager->get(EntityFactoryInterface::class);
908  }
909 }
loadWithFilter($printQuery=false, $logQuery=false)
Definition: Collection.php:699
$results
Definition: popup.phtml:13
addFieldToFilter($field, $condition)
Definition: Collection.php:170
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
loadData($printQuery=false, $logQuery=false)
Definition: Collection.php:675
$objectManager
Definition: bootstrap.php:17
$id
Definition: fieldset.phtml:14
toArray($arrRequiredFields=[])
Definition: Collection.php:732
setOrder($field, $direction=self::SORT_ORDER_DESC)
Definition: Collection.php:593
addFilter($field, $value, $type='and')
Definition: Collection.php:118
_getItemId(\Magento\Framework\DataObject $item)
Definition: Collection.php:434
$type
Definition: item.phtml:13
getItemByColumnValue($column, $value)
Definition: Collection.php:380
_toOptionArray($valueField='id', $labelField='name', $additional=[])
Definition: Collection.php:760
$value
Definition: gender.phtml:16
$page
Definition: pages.php:8
getItemsByColumnValue($column, $value)
Definition: Collection.php:360
load($printQuery=false, $logQuery=false)
Definition: Collection.php:687
walk($callback, array $args=[])
Definition: Collection.php:500
each($objMethod, $args=[])
Definition: Collection.php:524
$properties
Definition: categories.php:26
_toOptionHash($valueField='id', $labelField='name')
Definition: Collection.php:801
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
setDataToAll($key, $value=null)
Definition: Collection.php:548
__construct(EntityFactoryInterface $entityFactory)
Definition: Collection.php:105
addItem(\Magento\Framework\DataObject $item)
Definition: Collection.php:399
$code
Definition: info.phtml:12
if($currentSelectedMethod==$_code) $className
Definition: form.phtml:31