public function getSortedMatches($hostnameToMatch, array $domains)
    {
        $matchingDomains = [];
        $matchQualities = [];
        $hostnameToMatchPartsReverse = array_reverse(explode('.', $hostnameToMatch));

        foreach ($domains as $domain) {
            $domainHostname = $domain->getHostname();

            if ($hostnameToMatch === $domainHostname) {
                $matchQuality = self::EXACTMATCH;
            } else {
                $matchQuality = 0;
                $domainHostnamePartsReverse = array_reverse(explode('.', $domainHostname));
                foreach ($domainHostnamePartsReverse as $index => $domainHostnamePart) {
                    if (isset($hostnameToMatchPartsReverse[$index]) && $domainHostnamePart === $hostnameToMatchPartsReverse[$index]) {
                        $matchQuality++;
                    } else {
                        $matchQuality = self::NOMATCH;
                        break;
                    }
                }
            }

            if ($matchQuality > 0) {
                $matchingDomains[] = $domain;
                $matchQualities[] = $matchQuality;
            }
        }

        array_multisort($matchQualities, SORT_DESC, $matchingDomains);
        return $matchingDomains;
    }