private function getSortedDependencies(ContainerBuilder $container, array $options)
    {
        $ordered = array();
        $unordered = array();

        $serviceIds = $container->findTaggedServiceIds($options['tag']);

        foreach ($serviceIds as $serviceId => $tags) {

            if ($options['instanceof']) {
                $class = $container->getDefinition($serviceId)->getClass();
                if (!is_a($class, $options['instanceof'], true)) {
                    throw new \UnexpectedValueException(sprintf(
                        'Service "%s" tagged as "%s" must be an instance of class "%s". Found "%s" instead.',
                        $serviceId, $options['tag'], $options['instanceof'], $class
                    ));
                }
            }

            $service = $options['reference'] ? new Reference($serviceId) : $serviceId;
            foreach ($tags as $tag) {

                if (isset($tag['order']) && is_numeric($tag['order'])) {
                    $order = $tag['order'];
                    $dependencies = &$ordered[$order];

                } else {
                    $dependencies = &$unordered;
                }

                if ('key' === $options['index-by']) {
                    $name = $this->getAttribute($serviceId, $tag, $options['key']);

                    if ($options['multiple']) {
                        $dependencies[$name][] = $service;
                    } else {
                        $dependencies[$name] = $service;
                    }

                } elseif ('class' === $options['index-by']) {
                    $name = $container->getDefinition($serviceId)->getClass();

                    if ($options['multiple']) {
                        $dependencies[$name][] = $service;
                    } else {
                        $dependencies[$name] = $service;
                    }
                } else {
                    $dependencies[] = $service;
                }

                unset($dependencies);
            }
        }

        if (empty($ordered)) {
            return $unordered;
        }

        ksort($ordered);
        $ordered[] = $unordered;

        return call_user_func_array('array_merge_recursive', $ordered);
    }