<?php
namespace Newland\Toubiz\Sync\Neos\Service;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\ConfigurationManager;

/**
 * @Flow\Scope("prototype")
 */
class SortingService
{

    public function sortObjects(array $objectsToSort, string $sortByFieldName, array $sorting): array
    {
        $count = \count($objectsToSort);

        usort(
            $objectsToSort,
            function ($objectA, $objectB) use ($sorting, $count, $sortByFieldName) {
                $getter = 'get' . ucfirst($sortByFieldName);
                $indexA = array_search($objectA->$getter(), $sorting, true);
                if ($indexA === false) {
                    $indexA = $count;
                }
                $indexB = array_search($objectB->$getter(), $sorting, true);
                if ($indexB === false) {
                    $indexB = $count;
                }
                return $indexA - $indexB;
            }
        );

        return $objectsToSort;
    }
}
