diff --git a/app/code/Magento/CatalogInventory/Model/Source/Stock.php b/app/code/Magento/CatalogInventory/Model/Source/Stock.php index f64026cce23a5..9ed891d1dcc0f 100644 --- a/app/code/Magento/CatalogInventory/Model/Source/Stock.php +++ b/app/code/Magento/CatalogInventory/Model/Source/Stock.php @@ -26,4 +26,23 @@ public function getAllOptions() ['value' => \Magento\CatalogInventory\Model\Stock::STOCK_OUT_OF_STOCK, 'label' => __('Out of Stock')] ]; } + + /** + * Add Value Sort To Collection Select. + * + * @param \Magento\Eav\Model\Entity\Collection\AbstractCollection $collection + * @param string $dir + * + * @return $this + */ + public function addValueSortToCollection($collection, $dir = \Magento\Framework\Data\Collection::SORT_ORDER_DESC) + { + $collection->getSelect()->joinLeft( + ['stock_item_table' => 'cataloginventory_stock_item'], + "e.entity_id=stock_item_table.product_id", + [] + ); + $collection->getSelect()->order("stock_item_table.qty $dir"); + return $this; + } } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php new file mode 100644 index 0000000000000..11f41fcaf6d01 --- /dev/null +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/Source/StockTest.php @@ -0,0 +1,44 @@ +model = new \Magento\CatalogInventory\Model\Source\Stock(); + } + + public function testAddValueSortToCollection() + { + $selectMock = $this->createMock(\Magento\Framework\DB\Select::class); + $collectionMock = $this->createMock(\Magento\Eav\Model\Entity\Collection\AbstractCollection::class); + $collectionMock->expects($this->atLeastOnce())->method('getSelect')->willReturn($selectMock); + + $selectMock->expects($this->once()) + ->method('joinLeft') + ->with( + ['stock_item_table' => 'cataloginventory_stock_item'], + "e.entity_id=stock_item_table.product_id", + [] + ) + ->willReturnSelf(); + $selectMock->expects($this->once()) + ->method('order') + ->with("stock_item_table.qty DESC") + ->willReturnSelf(); + + $this->model->addValueSortToCollection($collectionMock); + } +}