组合 url 协议

@param $url
@param string $protocol
@return mixed
554423
public static function mergeUrlProtocol($url, $protocol = null)
    {
        $protocol   = is_null($protocol) ? static::getProtocol() : $protocol; // 协议类型
        $pattern    = '/^([a-zA-z]+)(:\/\/[^\s]*)/';                           // 正则表达式

        // 执行正则匹配
        preg_match($pattern, $url, $match);

        if ( static::isArray($match) ) {
            if ( isset($match[1]) ) {
                return preg_replace($pattern, $protocol . '$2', $url);
            }
        }

        return $protocol . '://' . $url;
    }
1201169
public function resolve($url)
    {
        $parts = parse_url($url);
        $parameters = [];
        $parameters['transport'] = isset($parts['scheme']) ? $parts['scheme'] : null;
        $parameters['encryption'] = null;

        // check for schemes such as 'ssl+smtp' and 'smtp+tls'
        if (strpos($parameters['transport'], '+') !== false) {
            $transports = explode('+', $parameters['transport']);
            if (count($transports) !== 2) {
                throw new \LogicException("Invalid transport in mailer url '$url'.");
            }

            if (in_array($transports[0], self::$valid_schemes)) {
                $parameters['transport'] = $transports[0];
                $parameters['encryption'] = $transports[1];
            } else {
                $parameters['transport'] = $transports[1];
                $parameters['encryption'] = $transports[0];
            }
        }

        $parameters['auth_mode'] = null;
        if (isset($parts['query'])) {
            parse_str($parts['query'], $query);

            // don't overwrite transport
            if (isset($query['transport'])) {
                unset($query['transport']);
            }

            // don't overwrite encryption if set
            if (isset($query['encryption']) && $parameters['encryption'] !== null) {
                unset($query['encryption']);
            }
            $parameters = array_merge($parameters, $query);
        }

        // extra parameters
        $parameters['host'] = isset($parts['host']) ? $parts['host'] : null;
        $parameters['port'] = isset($parts['port']) ? $parts['port'] : false;
        $parameters['user'] = isset($parts['user']) ? $parts['user'] : null;
        $parameters['password'] = isset($parts['pass']) ? $parts['pass'] : null;

        // some validation
        if ($parameters['transport'] !== null && !in_array($parameters['transport'], self::$valid_schemes)) {
            throw new \LogicException("Invalid transport scheme '{$parameters['transport']}'.");
        }

        if ($parameters['encryption'] !== null && !in_array($parameters['encryption'], self::$valid_encryption)) {
            throw new \LogicException("Invalid encryption method '{$parameters['encryption']}'.");
        }

        if ($parameters['auth_mode'] !== null && !in_array($parameters['auth_mode'], self::$valid_auth_modes)) {
            throw new \LogicException("Invalid auth_mode '{$parameters['auth_mode']}'.");
        }

        // some extra checks for specific cases
        if ($parameters['transport'] === null) {
            if ($url === 'sendmail://' || $url === 'sendmail') {
                $parameters['transport'] = 'sendmail';
            } else if ($url === 'mail://' || $url === 'mail') {
                $parameters['transport'] = 'mail';
            } else if (strpos($url, 'gmail://') === 0) {
                $userpass = substr($url, 8);
                $userpassparts = explode(':', $userpass, 2);
                if (count($userpassparts) === 2) {
                    $parameters['transport'] = 'gmail';
                    $parameters['user'] = $userpassparts[0];
                    $parameters['password'] = $userpassparts[1];
                }
            } else {
                throw new \LogicException("Invalid url specified '{$url}'");
            }
        }

        // disable transport if requested
        if ($parameters['transport'] === 'none' || $parameters['transport'] === 'null') {
            $parameters['transport'] = null;
        }

        return $parameters;
    }
586855
public function siteUrl($uri = '', $protocol = '')
    {
        if (!isset($uri)) {
            $base_url = NULL;
        } elseif (trim($uri) === '') {
            $base_url = '';
        } else {
            $base_url = rtrim($uri, '/') . '/';
        }
        if (isset($protocol)) {
            // For protocol-relative links
            if ($protocol === '') {
                $base_url = substr($base_url, strpos($base_url, '//'));
            } else {
                $base_url = $protocol . substr($base_url, strpos($base_url, '://'));
            }
        }
        if (empty($uri)) {
            return $base_url;
        }
        if (is_array($uri)) {
            $uri = http_build_query($uri);
        }
        $suffix = $this->siteExt;
        if ($suffix !== '') {
            if (($offset = strpos($uri, '?')) !== FALSE) {
                $uri = substr($uri, 0, $offset) . $suffix . substr($uri, $offset);
            } else {
                $uri .= $suffix;
            }
        }

        return trim($base_url) . trim($uri);

    }
1150909
private function processUrl($url)
    {
        $vars = [
            '{CLIENT_ID}'    => $this->getClientId(),
            '{REDIRECT_URI}' => $this->getRedirectURI(),
            '{SCOPE}'        => $this->getScope(),
            '{STATE}'        => $this->getState(),
            " "              => '',
            "\n"             => '',
            "\r"             => '',
            "\t"             => ''
        ];

        $url = str_replace(array_keys($vars), array_values($vars), $url);

        return $url;
    }
553672
protected function buildUrl($url)
    {
        return Controller::join_links(
            Director::baseURL(),
            Config::inst()->get('DocumentationViewer', 'link_base'),
            $url,
            '/'
        );
    }
394755
public static String getProtocol(String url)
  {
    if(url == null) {
      return null;
    }
    int protocolSeparatorIndex = url.indexOf("://");
    if(protocolSeparatorIndex == -1) {
      return null;
    }
    return url.substring(0, protocolSeparatorIndex).toLowerCase();
  }
1288387
public static function parseUrl($url)
    {
        $parseUrl = parse_url($url);
        if (isset($parseUrl['query'])) {
            // 修复Pjax参数。该参数带#符号，导致该参数后的其他参数被标识为fragment
            if (strpos($parseUrl['query'], '_pjax') !== false && isset($parseUrl['fragment'])) {
                $parseUrl['query'] .= $parseUrl['fragment'];
                unset($parseUrl['fragment']);
            }
            $parseUrl['query'] = self::convertUrlQuery($parseUrl['query']);
        }
        
        return $parseUrl;
    }
583213
public function getEndpointAsUrl($port, $protocol = 'tcp')
    {
        if (!$this->hasEndpoint($port, $protocol)) {
            throw new Exception('Endpoint is not available');
        }

        $key = $port . '/' . $protocol;

        return Url::fromString($this->endpoints[$key]);
    }
196414
public function findByUrl($url)
    {
        $this->url = $url;
        $url = RouterHelper::normalizeUrl($url);

        /**
         * @event cms.router.beforeRoute
         * Fires before the CMS Router handles a route
         *
         * Example usage:
         *
         *     Event::listen('cms.router.beforeRoute', function ((string) $url, (\Cms\Classes\Router) $thisRouterInstance) {
         *         return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
         *     });
         *
         */
        $apiResult = Event::fire('cms.router.beforeRoute', [$url, $this], true);
        if ($apiResult !== null) {
            return $apiResult;
        }

        for ($pass = 1; $pass <= 2; $pass++) {
            $fileName = null;
            $urlList = [];

            $cacheable = Config::get('cms.enableRoutesCache');
            if ($cacheable) {
                $fileName = $this->getCachedUrlFileName($url, $urlList);
                if (is_array($fileName)) {
                    list($fileName, $this->parameters) = $fileName;
                }
            }

            /*
             * Find the page by URL and cache the route
             */
            if (!$fileName) {
                $router = $this->getRouterObject();
                if ($router->match($url)) {
                    $this->parameters = $router->getParameters();

                    $fileName = $router->matchedRoute();

                    if ($cacheable) {
                        if (!$urlList || !is_array($urlList)) {
                            $urlList = [];
                        }

                        $urlList[$url] = !empty($this->parameters)
                            ? [$fileName, $this->parameters]
                            : $fileName;

                        $key = $this->getUrlListCacheKey();
                        Cache::put(
                            $key,
                            base64_encode(serialize($urlList)),
                            Config::get('cms.urlCacheTtl', 1)
                        );
                    }
                }
            }

            /*
             * Return the page
             */
            if ($fileName) {
                if (($page = Page::loadCached($this->theme, $fileName)) === null) {
                    /*
                     * If the page was not found on the disk, clear the URL cache
                     * and repeat the routing process.
                     */
                    if ($pass == 1) {
                        $this->clearCache();
                        continue;
                    }

                    return null;
                }

                return $page;
            }

            return null;
        }
    }
449028
public function setURL($url = '')
    {
        try {
            if (mb_strlen($url) > 0) {
                if (substr($url, 0, 8) == 'https://') {
                    $this->isSSL = TRUE;
                    $this->debug->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL);
                } elseif (substr($url, 0, 7) == 'http://') {
                    $this->isSSL = TRUE;
                    $this->debug->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL);
                }
            }
            $this->url = $url;
        }
        catch (Exception $e) {
            $this->url = NULL;
            $message   = "Error: " . __CLASS__ . ": Invalid protocol specified. URL must start with http:// or https:// - " . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return $message;
        }
        $this->debug->debug(__FUNCTION__, 'Endpoint URL to Request: ', $this->url);

        return $this;
    }
888679
function uriToUrl(uri, protocol, port) {
  // just pretend to start with http; it's overwritten two lines down
  const parts = urlParse.parse('http://' + uri);

  parts.protocol = protocol || 'http';
  parts.port = port || process.env.PORT;
  delete parts.host;

  if (parts.port &&
    (parts.protocol === 'http' && parts.port.toString() === '80') ||
    parts.protocol === 'https' && parts.port.toString() === '443'
  ) {
    delete parts.port;
  }

  return parts.format();
}
521959
protected function parseUrl($url, $parameters)
    {
        // If provided $url is a route name...
        if ($this->route->has($url)) {
            $url = $this->url->route($url, $parameters);
        } else {
            $url = $this->url->to($url, $parameters);
        }

        return $url;
    }
893400
private function _parseUrl($url) {
    $parse = parse_url($url);
    if (empty($parse) || !is_array($parse)) {
      throw new Exception("Host is empty.");
    }

    if (!isset($parse['port']) || !$parse['port']) {
      $parse['port'] = '80';
    }

    $parse['host'] = str_replace(
        array('http://', 'https://'),
        array('', 'ssl://'),
        $parse['scheme'] . "://"
    ) . $parse['host'];

    $parse["path"] = isset($parse["path"]) ? $parse["path"] : '/';
    $query = isset($parse['query']) ? $parse['query'] : '';

    $path = str_replace(array('\\', '//'), '/', $parse['path']);
    $parse['path'] = $query ? $path . "?" . $query : $path;

    return $parse;
  }
1263443
private function matchUrl($url)
    {
        $request = Request::create($url);
        $this->requestAnalyzer->analyze($request);

        try {
            return null !== $this->router->matchRequest($request);
        } catch (ResourceNotFoundException $exception) {
            return false;
        }
    }
473727
protected function parseUrl($url)
    {
        $depr = $this->rule->getConfig('app.pathinfo_depr');
        $bind = $this->rule->getRouter()->getBind();

        if (!empty($bind) && preg_match('/^[a-z]/is', $bind)) {
            $bind = str_replace('/', $depr, $bind);
            // 如果有模块/控制器绑定
            $url = $bind . ('.' != substr($bind, -1) ? $depr : '') . ltrim($url, $depr);
        }

        list($path, $var) = $this->rule->parseUrlPath($url);

        return $path;

//        // 解析模块
//        $module = array_shift($path);
//
//        if ($this->param['auto_search']) {
//            $controller = $this->autoFindController($module, $path);
//        } else {
//            // 解析控制器
//            $controller = !empty($path) ? array_shift($path) : null;
//        }
//
//        // 解析操作
//        $action = !empty($path) ? array_shift($path) : null;
//
//        // 解析额外参数
//        if ($path) {
//            if ($this->rule->getConfig('url_param_type')) {
//                $var += $path;
//            } else {
//                preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
//                    $var[$match[1]] = strip_tags($match[2]);
//                }, implode('|', $path));
//            }
//        }
//
//        $panDomain = Request::panDomain();
//
//        if ($panDomain && $key = array_search('*', $var)) {
//            // 泛域名赋值
//            $var[$key] = $panDomain;
//        }
//
//        // 设置当前请求的参数
//        Request::setRouteVars($var);
//
//        // 封装路由
//        $route = [$module, $controller, $action];
//
//        if ($this->hasDefinedRoute($route, $bind)) {
//            throw new HttpException(404, 'invalid request:' . str_replace('|', $depr, $url));
//        }
//
//        return $route;
    }
330418
private static function getPartition(string $url): ?Partition
    {
        $urlParts = explode('://', $url);
        $protocol = array_shift($urlParts);

        return self::$partitions[$protocol] ?? null;
    }
1073144
private function buildUrl($url, $parameters)
    {
        $prams_former = '?';

        foreach ($parameters as $key => $value) {
            $prams_former = $prams_former.$key.'='.$value.'&';
        }

        return $url.substr($prams_former, 0, -1);
    }