URL parser : load and parse the current URL

The class will pass arguments values to any `$this->fromUrlParam($value)` method for the
parameter named `param`.
519359
protected function _parseUrl()
    {
        $url_frgts = UrlHelper::parse($this->getUrl());
        $route = array('all'=>array());
        if (!empty($url_frgts['params'])) {
            $frgts = array();
            $url_args = $this->getArgumentsMap();
            foreach ($url_frgts['params'] as $_var=>$_val) {
                $_meth = 'fromUrl'.TextHelper::toCamelCase($_var);
                if (method_exists($this, $_meth)) {
                    $_val = call_user_func_array(array($this, $_meth), array($_val));
                }
                if (isset($url_args[$_var])) {
                    $route[$url_args[$_var]] = $_val;
                } else {
                    $route['all'][$_var] = $_val;
                }
            }
        }
        $this->setRouteParsed($route);
    }
1131858
function setUrl( $value, $params=FALSE ) {
    $this->url['value']   = $value;
    if( empty( $this->url['value'] ))
      return;
    $this->url['params'] = $this->_setParams( $params );
  }
104721
def from_url(cls, url, **kwargs):
        """"""
        url = urllib3.util.parse_url(url)
        if url.host:
            kwargs.setdefault('host', url.host)

        if url.port:
            kwargs.setdefault('port', url.port)

        if url.scheme == 'https':
            kwargs.setdefault('connection_class', urllib3.HTTPSConnectionPool)

        return cls(**kwargs)
657379
protected function parseUrlParams($url_params)
    {
        if ($url_params != '#' && (is_array($url_params) || (strpos($url_params, 'http') !== 0 && strpos($url_params, '/') !== 0))) {
            if (!is_array($url_params))
                $url_params = array($url_params);
            $url_to = Rails::application()->router()->urlFor($url_params, true);
        } else {
            $url_to = $url_params;
        }
        return $url_to;
    }
754933
def _parse_url_and_validate(cls, url):
        
        parsed_url = urlparse(url)
        if parsed_url.scheme and parsed_url.netloc:
            final_url = parsed_url.geturl()
        else:
            raise BadURLException
        return final_url
151701
public static function parse($url)
    {
        $scheme = substr($url, 0, strpos($url, ':'));
        if (strpos($scheme, '+')) {
            $scheme = substr($scheme, 0, strpos($scheme, '+'));
        }

        if (!$scheme) {
            throw new \Exception(sprintf('The url \'%s\' could not be parsed', $url));
        }

        if (isset(static::$schemeMap[$scheme])) {
            $className = static::$schemeMap[$scheme];
        } else {
            $className  = static::currentNamespace() . '\\' . ucfirst($scheme) . 'Dsn';
            if (!class_exists($className)) {
                $className  = static::currentClass();
            }
        }
        return new $className($url);
    }
1241957
function (url, paramName, paramValue)
    {
      // if the specified url is valid
      var urlAsObject = Url.parse(url);
      if (urlAsObject)
      {
        // if the url already has query parameters, use '&' as the separator
        // when appending the additional query parameter, otherwise use '?'
        url += (urlAsObject.search ? '&' : '?') + paramName + '=' + paramValue;
      }

      return url;
    }
1113831
public function parseUrlParameters()
    {
        $urlParts = explode('/', $this->url);
        $this->parameters = [];
        foreach ($urlParts as $index => $part) {
            if (mb_substr($part, 0, 1) === '{' && mb_substr($part, -1) === '}') {
                $this->parameters[$index] = mb_substr($part, 1, -1);
            }
        }
        return $this;
    }
1312531
private function _set_params()
    {
        // Get values from request
        $params = \Request::route('params');
        $filepath = $this->config['abs_path'] . '/' . \Request::route('imagepath');
        
        // echo $params; exit;
        
        // If enforcing params, ensure it's a match
        if ($this->config['enforce_presets'] && !in_array($params, $this->config['presets'])) {
            abort(404);
        }
        
        $image = new Image();
        $image->configure(config('image'));
        if (function_exists('exif_read_data')) {
            $this->image = $image->make($filepath)->orientate();
        } else {
            $this->image = $image->make($filepath);
        }
        
        // The parameters are separated by hyphens
        $raw_params = explode('-', $params);
        
        // Update param values from passed values
        foreach ($raw_params as $raw_param) {
            $name = $raw_param[0];
            $value = substr($raw_param, 1, strlen($raw_param) - 1);
            
            if ($name == 'c') {
                $this->url_params[$name] = TRUE;
                
                // When croping, we must have a width and height to pass to imagecreatetruecolor method
                // Make width the height or vice versa if either is not passed
                if (empty($this->url_params['w'])) {
                    $this->url_params['w'] = $this->url_params['h'];
                }
                if (empty($this->url_params['h'])) {
                    $this->url_params['h'] = $this->url_params['w'];
                }
            } elseif (key_exists($name, $this->url_params)) {
                // Remaining expected params (w, h, q)
                $this->url_params[$name] = $value;
            } else {
                // Watermarks or invalid params
                $this->url_params[$raw_param] = $raw_param;
            }
        }
        
        // Do not scale up images
        if (! $this->config['scale_up']) {
            if ($this->url_params['w'] > $this->image->width()) {
                $this->url_params['w'] = $this->image->width();
            }
            if ($this->url_params['h'] > $this->image->height()) {
                $this->url_params['h'] = $this->image->height();
            }
        }
        
        // Must have at least a width or height
        if (empty($this->url_params['w']) and empty($this->url_params['h'])) {
            throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(
                ':uri' => Request::$current->uri()
            ));
        }
        
        // Set the url filepath
        $this->source_file = $filepath;
    }
716591
def id_from_url(url, param_name: str) -> int:
    
    if url is None:
        raise ValueError('url is none')
    elif isinstance(url, int):
        # Seems to already be the url.
        return url
    if not url:
        raise ValueError('Seems to be empty')

    try:
        return int(url)
    except ValueError:
        pass

    parsed = urlparse(url)
    try:
        resource_url = app.url_map.bind(parsed.netloc).match(
            parsed.path
        )
    except NotFound:
        raise ValueError('No URL found')

    if param_name in resource_url[1]:
        return resource_url[1][param_name]
    else:
        raise ValueError(
            'Parameter {name} could not be extracted'.format(
                name=param_name
            )
        )
1039965
public function parse() {
        global $argv;

        $options = array();
        $parameters = array();
        $argc = count( $argv );
        $paramCount = count( $this->parameters );
        
        //get parameters
        if( $argc - 1 < $paramCount ) {
            throw new \Exception("The command requires $paramCount parameters.");
        }
        
        //last items are the params
        for( $i = $paramCount - 1; $i >= 0; $i-- ) {
            $this->abstractParameters[$this->parameters[$i]] = $argv[$argc - $i - 1];
        }
        
        //go through each arg
        for( $i = 1; $i < $argc - $paramCount; $i++ ) {
            $arg = $argv[$i];
            
            //cannot start without a switch
            if( !$this->isOption( $arg ) ) {
                throw new \Exception("Invalid argument \"$arg\".");
            }
            
            //check if it's a valid option
            $option = $arg[1];

            if( $this->isParam( $option ) ) {
                //the arg stands on its own, such as -f, not -ffile.txt
                //set next as its value, move $i ahead
                if( $this->isSolitary( $arg ) ) {
                    //last item
                    if( $i == $argc - $paramCount - 1 ) {
                        throw new \Exception("Parameter does not follow the option \"$option\".");
                    }
                    
                    $this->abstractOptions[$option] = $argv[$i+1];
                    $i++;
                } else {
                    $this->abstractOptions[$option] = substr( $arg, 2 );
                }
            } else if( $this->isSwitch( $option ) ) {
                //loop through all switches in the param
                for( $i = 1; $i < strlen( $param ) - 1; $i++ ) {
                    $s = $arg[$i];
                    
                    //not a switch
                    if( !$this->isSwitch( $arg[$i] ) ) {
                        throw new \Exception("An invalid switch \"$s\" was provided.");
                    }
                    
                    $this->abstractOptions[$s] = true;
                }
            }
        }
    }
1145547
private function getUrlHelper() : UrlHelper
    {
        if (null === $this->urlHelper) {
            $this->urlHelper = new UrlHelper(new View());
        }

        return $this->urlHelper;
    }
837204
public function parse_value($value) {

        if (strpos($value, '$LtiLink.custom.url') !== false) {
            $id = optional_param('id', 0, PARAM_INT); // Course Module ID.
            if (!empty($id)) {
                $cm = get_coursemodule_from_id('lti', $id, 0, false, MUST_EXIST);
                $this->params['link_id'] = $cm->instance;
            }
            $value = str_replace('$LtiLink.custom.url', parent::get_endpoint(), $value);
        }
        return $value;

    }
642853
def parse_params(params)
      args = params.split(/\s+/).map(&:strip)
      invalid_args!(args) unless args.any?

      if args[0].to_s == OEMBED_ARG # TODO: remove after deprecation cycle
        arguments_deprecation_warning(args)
        args.shift
      end

      url, *api_args = args
      ApiRequest.new(url, parse_args(api_args))
    end
431931
def get(self, **url_params):
        
        if url_params:
            self.http_method_args["params"].update(url_params)
        return self.http_method("GET")
548714
public function parse_value($value) {
        global $COURSE;

        if (strpos($value, '$LineItems.url') !== false) {
            $this->params['context_id'] = $COURSE->id;
            $value = str_replace('$LineItems.url', parent::get_endpoint(), $value);
        }

        return $value;

    }
624643
def _parse_parameters(self, resource, params):
        '''
        '''
        # remove params from resource URI (needed for paginated stuff)
        parsed_uri = urlparse(resource)
        qs = parsed_uri.query
        resource = urlunparse(parsed_uri._replace(query=''))
        prms = {}
        for tup in parse_qsl(qs):
            prms[tup[0]] = tup[1]

        # params supplied to self.get() override parsed params
        for key in params:
            prms[key] = params[key]
        return resource, prms