protected function rewriteRelative($url, $sourceUrl, $bundleUrl)
    {
        $sourceUrl = trim($sourceUrl, '/');
        $bundleUrl = trim($bundleUrl, '/');

        if ($bundleUrl === $sourceUrl) {
            return $url;
        }

        if ('' === $sourceUrl) {
            return str_repeat('../', count(explode('/', $bundleUrl))) . $url;
        }

        if ('' === $bundleUrl) {
            return $this->canonicalize($sourceUrl . '/' . $url);
        }

        if (0 === strpos($bundleUrl, $sourceUrl)) {
            $prepend = $bundleUrl;
            $count = 0;

            while ($prepend !== $sourceUrl) {
                $count++;
                $prepend = dirname($prepend);
            }

            return str_repeat('../', $count) . $url;
        } elseif (0 === strpos($sourceUrl, $bundleUrl)) {
            $path = $sourceUrl;
            while (0 === strpos($url, '../') && $path !== $bundleUrl) {
                $path = dirname($path);
                $url = substr($url, 3);
            }

            return $url;
        } else {
            $prepend = str_repeat('../', count(explode('/', $bundleUrl)));
            $path = $sourceUrl . '/' . $url;

            return $prepend . $this->canonicalize($path);
        }
    }