<?php
namespace MNM\Spitzner\Plugin;

class FilterproductsSortByProductAttribute
{
    /**
     * @param \Smartwave\Filterproducts\Block\Home\LatestList $subject
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $result
     * @return string
     */
    public function afterGetProducts(\Smartwave\Filterproducts\Block\Home\LatestList $subject, 
                                    \Magento\Catalog\Model\ResourceModel\Product\Collection $result)
    {
        //check if attribute set
        $sortBy = $subject->getData('sort_by');
        
        if($sortBy)
        {
            //clear sorting
            $result->getSelect()->reset(\Magento\Framework\DB\Select::ORDER);
            
            //set to attribute
            $result->addAttributeToSort($sortBy, 'asc');
        }
        
        return $result;
    }
}