Search code examples
phpusort

Usort being skipped unless watched


This is a strange situation, I have a usort function that seems to work fine only if I am monitoring code execution through xdebug. No clue why.

It's almost as if the usort call is being skipped unless it's being watched. Just looking for any input on why this might occur, if anyone else has experienced this or has an idea.

Here's the code, maybe I'm missing something.

private function getProjectHistories() {
    $query = $this->getEntityManager()->createQueryBuilder()
            ->select('p')
            ->from('App:ProjectHistory', 'p')
            ->where('p.profile = :user_id')
            ->setParameter('user_id', $this->getUserId())
            ->getQuery();

    $histories_array = $query->getResult(Query::HYDRATE_ARRAY);
    usort($histories_array, [$this, 'historyArraySort']);

    return $histories_array;
}

/**
 * Sorts histories by start date in ascending order
 * 
 * @param array $hist1 history array
 * @param array $hist2 history array
 * @return int Sort value
 */
private function historyArraySort($hist1, $hist2) {
    $histories_are_arrays = (is_array($hist1) && is_array($hist2));
    $histories_have_starts = ($histories_are_arrays && array_key_exists('start', $hist1) && array_key_exists('start', $hist2));
    $starts_have_dates = ($histories_have_starts && is_object($hist1['start']) && property_exists($hist1['start'], 'date') && is_object($hist2['start']) && property_exists($hist2['start'], 'date'));
    if ($starts_have_dates) {
        return $hist1['start']->date <=> $hist2['start']->date;
    }
}

Solution

  • Sorts histories by start date in ascending order

    Sounds like all you needed is to add an ORDER BY on your query

    ->orderBy('start')