_buildParamStr
拼接参数
@param  array $requestParams 请求参数
@param  string $requestMethod 请求方法
@return string
7258
protected function _buildParamStr($requestParams, $requestMethod = 'POST')
    {
        $paramStr = '';
        ksort($requestParams);
        $i = 0;
        foreach ($requestParams as $key => $value) {
            if ($key == 'Signature') {
                continue;
            }
            // 排除上传文件的参数
            if ($requestMethod == 'POST' && substr($value, 0, 1) == '@') {
                continue;
            }
            // 把 参数中的 _ 替换成 .
            if (strpos($key, '_')) {
                $key = str_replace('_', '.', $key);
            }

            if ($i == 0) {
                $paramStr .= '?';
            } else {
                $paramStr .= '&';
            }
            $paramStr .= $key . '=' . $value;
            ++$i;
        }

        return $paramStr;
    }
1134843
protected function buildUri(Actions\ActionsInterface $action, array $requestParams)
    {
        $uri = $this->connection->getEndpoint() . '/' . $action->getAction();

        if ($this->connection->getHttpMethod() === Request::METHOD_GET) {
            $uri .= '?' . http_build_query($requestParams);
        }

        return new Uri($uri);
    }
325522
public function buildBaseString(array $oauthParams)
    {
        $tempArray = array();
        ksort($oauthParams);

        if ($oauthParams['oauth_callback'] === '') {
            unset($oauthParams['oauth_callback']);
        }

        if ($oauthParams['oauth_verifier'] === '') {
            unset($oauthParams['oauth_verifier']);
        }

        array_walk($oauthParams, function($value, $key) use (&$tempArray) {
            $tempArray[] = $key . '=' . rawurlencode($value);
        });

        $parsedUrl = parse_url($this->resourceURL);
        $baseString = $this->httpMethod .'&';
        $baseString .= rawurlencode($parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path']);
        $baseString .= (isset($parsedUrl['query'])) ? '&' . rawurlencode($parsedUrl['query']) . '%26' : '&';
        $baseString .= rawurlencode(implode('&', $tempArray));

        array_walk($this->postFields, function($value, $key) use (&$baseString) {
            $baseString .= '%26' . $key . rawurlencode('=' . $value);
        });

        return $baseString;
    }
396864
public static function buildQueryString($params, $separator = '&', $key = null)
    {
        $query = '';
        foreach ($params as $k => $v) {
            $k = urlencode($k);
            if (!empty($key)) {
                $k = $key.'['.$k.']';
            }
            if (is_null($v)) {
                continue;
            } elseif (is_array($v)) {
                $query .= call_user_func(array(__CLASS__, __FUNCTION__), $v, $separator, $k).$separator;
            } else {
                if ($v === false) {
                    $v = 0;
                } elseif ($v === true) {
                    $v = '';
                }
                $v = str_replace(array('%2F','%2C','%3A','%7C'), array('/',',',':','|'), urlencode($v));
                $query .= $k.'='.$v.$separator;
            }
        }
        $query = rtrim(str_replace('='.$separator, $separator, $query), $separator);
        return $query;
    }
627548
public function retrieveBlocksByForm($requestParams)
    {
        $requiredParams = array("name");
        return $this->client->request($requestParams, $this->_endpoint . "/" . self::FORM_BLOCKS_BY_NAME, "get", $requiredParams, $options = NULL);
    }
1341239
private function buildUrl(DateTimeInterface $requestedDate): string
    {
        return self::URL.'?'.http_build_query([self::DATE_QUERY_PARAMETER_NAME => $requestedDate->format(self::DATE_FORMAT)]);
    }
933988
private function arrayFrom($requestMethod): array
    {
        if (is_string($requestMethod)) {
            return [$requestMethod];
        }

        if (null === $requestMethod) {
            return [Http::GET, Http::HEAD, Http::POST, Http::PUT, Http::DELETE];
        }

        if (is_array($requestMethod)) {
            return $requestMethod;
        }

        throw new \InvalidArgumentException(
                'Given request method must be null, a string or an array, but received '
                . typeOf($requestMethod)
        );
    }
856730
private function buildUrl($method, $params)
    {
        $url = $this->address.$method;

        return $url."?".http_build_query($params);
    }
769110
public function params($requestParams): array
    {
        // apply type and default value for request params
        $params = [];
        foreach ($this->params as $param => $type) {
            if (isset($requestParams[$param])) {
                switch ($type) {
                    case 'bool':
                    case 'boolean':
                        $params[] = (bool)$requestParams[$param];
                        break;
                    case 'int':
                    case 'integer':
                        $params[] = (int)$requestParams[$param];
                        break;
                    case 'float':
                        $params[] = (float)$requestParams[$param];
                        break;
                    case 'string':
                        $params[] = (string)$requestParams[$param];
                        break;
                    case 'array':
                        $params[] = (array)$requestParams[$param];
                        break;
                    default:
                        $params[] = $requestParams[$param];
                        break;
                }
            } elseif (isset($this->values[$param])) {
                $params[] = $this->values[$param];
            } else {
                $params[] = null;
            }
        }
        return $params;
    }
983318
protected function _buildDataAttrs(array $param = array())
    {
        $return = '';
        foreach ($param as $data => $val) {
            $dKey = 'data-' . trim($data);

            if (is_object($val)) {
                $val = (array) $val;
            }

            if (is_array($val)) {
                $val = str_replace('"', '\'', json_encode($val));
                $return .= $this->_buildAttr($dKey, $val);
                continue;
            }

            $return .= $this->_buildAttr($dKey, $val);
        }

        return $return;
    }
926799
private function calculateRequestPathFormat($resourceMethod, array $resourceMethodConfiguration): string
    {
        if (false === array_key_exists($resourceMethod, $resourceMethodConfiguration)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Resource "%s" Method not found in configuration keys [%s]',
                    $resourceMethod,
                    implode(', ', array_keys($resourceMethodConfiguration))
                )
            );
        }

        return $resourceMethodConfiguration[$resourceMethod];
    }
1206574
public static function generateExecuteActionRequest( $requestName, $parameters = null, $requestType = null ) {
        /* Generate the ExecuteAction message */
        $executeActionRequestDOM = new DOMDocument();

        $executeActionNode = $executeActionRequestDOM->appendChild( $executeActionRequestDOM->createElementNS( 'http://schemas.microsoft.com/xrm/2011/Contracts/Services', 'Execute' ) );
        $executeActionNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:i', 'http://www.w3.org/2001/XMLSchema-instance' );

        $requestNode = $executeActionNode->appendChild( $executeActionRequestDOM->createElement( 'request' ) );
        $requestNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:b', 'http://schemas.microsoft.com/xrm/2011/Contracts' );
        /* Set request type */
        if ( $requestType ) {
            $requestNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:e', 'http://schemas.microsoft.com/crm/2011/Contracts' );
            $requestNode->setAttribute( 'i:type', 'e:' . $requestType );
        }

        $parametersNode = $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:Parameters' ) );
        $parametersNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:c', 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' );

        if ( $parameters != null && is_array( $parameters ) ) {

            foreach ( $parameters as $parameter ) {
                /* Create a Key/Value Pair of String/Any Type */
                $propertyNode = $parametersNode->appendChild( $executeActionRequestDOM->createElement( 'b:KeyValuePairOfstringanyType' ) );
                /* Set the Property Name */
                $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:key', $parameter["key"] ) );
                /* Determine the Type, Value and XML Namespace for this field */
                $xmlValue      = $parameter["value"];
                $xmlValueChild = null;
                $xmlType       = strtolower( $parameter["type"] );
                $xmlTypeNS     = 'http://www.w3.org/2001/XMLSchema';
                /* Special Handing for certain types of field */
                switch ( $xmlType ) {
                    case 'entityreference':
                        /* AlexaCRM\CRMToolkit\Entity\EntityReference - Get a entity xml structure */
                        $xmlType = 'EntityReference';
                        /** @var Entity $entity */
                        $entity      = $xmlValue;
                        $xmlTypeNS   = 'http://schemas.microsoft.com/xrm/2011/Contracts';
                        $entityValue = $executeActionRequestDOM->createElement('c:value');
                        $entityValue->appendChild($executeActionRequestDOM->createElement('b:Id', $entity->ID));
                        $entityValue->appendChild($executeActionRequestDOM->createElement('b:LogicalName', $entity->LogicalName));
                        $xmlValue = null;
                        break;

                    case 'arrayofguid':
						$xmlType = 'ArrayOfguid';
						$arrayOfguids = $xmlValue;
						$xmlTypeNS = 'http://schemas.microsoft.com/2003/10/Serialization/Arrays';
						$entityValue = $executeActionRequestDOM->createElement('c:value');
						foreach ( $arrayOfguids as $contact_guid ) {
							$entityValue->appendChild($executeActionRequestDOM->createElement( 'd:guid', $contact_guid ));
						}; // end foreach
						$xmlValue = null;
						break;

                    case 'memo':
                        /* Memo - This gets treated as a normal String */
                        $xmlType = 'string';
                        break;
                    case 'integer':
                        /* Integer - This gets treated as an "int" */
                        $xmlType = 'int';
                        break;
                    case 'uniqueidentifier':
                        /* Uniqueidentifier - This gets treated as a guid */
                        $xmlType = 'guid';
                        break;
                    case 'money':
                        $xmlType = 'Money';
                        //$xmlTypeNS = NULL;
                        $xmlValue = $executeActionRequestDOM->createElement( 'c:Value', $parameter["value"] );
                        break;
                    case 'picklist':
                    case 'state':
                    case 'status':
                        /* OptionSetValue - Just get the numerical value, but as an XML structure */
                        $xmlType       = 'OptionSetValue';
                        $xmlTypeNS     = 'http://schemas.microsoft.com/xrm/2011/Contracts';
                        $xmlValue      = null;
                        $xmlValueChild = $executeActionRequestDOM->createElement( 'b:Value', $parameter["value"] );
                        break;
                    case 'boolean':
                        /* Boolean - Just get the numerical value */
                        $xmlValue = ( $parameter["value"] ) ? "true" : "false";
                        break;
                    case 'guid':
                        $xmlType   = 'guid';
                        $xmlTypeNS = 'http://schemas.microsoft.com/2003/10/Serialization/';
                        break;
                    case 'base64binary':
                        $xmlType = 'base64Binary';
                        break;
                    case 'string':
                    case 'int':
                    case 'decimal':
                    case 'double':
                        /* No special handling for these types */
                        break;
                    default:
                        /* If we're using Default, Warn user that the XML handling is not defined */
                        trigger_error( 'No Create/Update handling implemented for type ' . $xmlType . ' used by field ' . $parameter["key"], E_USER_WARNING );
                }
                /* Now create the XML Node for the Value */
                $valueNode = isset($entityValue) ? $propertyNode->appendChild($entityValue) :
                    $propertyNode->appendChild($executeActionRequestDOM->createElement('c:value'));
                $entityValue = null;
                /* Set the Type of the Value */
                $valueNode->setAttribute( 'i:type', 'd:' . $xmlType );
                $valueNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', $xmlTypeNS );
                /* If there is a child node needed, append it */
                if ( $xmlValueChild != null ) {
                    $valueNode->appendChild( $xmlValueChild );
                }
                /* If there is a value, set it */
                if ( $xmlValue != null ) {
                    $valueNode->appendChild( new DOMText( $xmlValue ) );
                }
            }
        }
        $requestIdNode = $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:RequestId' ) );
        $requestIdNode->setAttribute( 'i:nil', 'true' );
        $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:RequestName', $requestName ) );

        return $executeActionNode;
    }
39255
public static function fromRequest($httpMethod = null, $httpUrl = null, $parameters = null)
    {
        $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
            ? 'http'
            : 'https';
        @$httpUrl or $httpUrl = $scheme .
            '://' . $_SERVER['HTTP_HOST'] .
            ':' .
            $_SERVER['SERVER_PORT'] .
            $_SERVER['REQUEST_URI'];
        @$httpMethod or $httpMethod = $_SERVER['REQUEST_METHOD'];

        // We weren't handed any parameters, so let's find the ones relevant to
        // this request.
        // If you run XML-RPC or similar you should use this to provide your own
        // parsed parameter-list
        if (!$parameters) {
            // Find request headers
            $requestHeaders = Util::getHeaders();

            // Parse the query-string to find GET parameters
            $parameters = Util::parseParameters($_SERVER['QUERY_STRING']);

            // It's a POST request of the proper content-type, so parse POST
            // parameters and add those overriding any duplicates from GET
            if ($httpMethod == "POST"
                && @strstr(
                    $requestHeaders["Content-Type"],
                    "application/x-www-form-urlencoded"
                )
            ) {
                $post_data = Util::parseParameters(
                    file_get_contents('php://input')
                );
                $parameters = array_merge($parameters, $post_data);
            }

            // We have a Authorization-header with OAuth data. Parse the header
            // and add those overriding any duplicates from GET or POST
            if (@substr($requestHeaders['Authorization'], 0, 6) == "OAuth ") {
                $headerParameters = Util::splitHeader(
                    $requestHeaders['Authorization']
                );
                $parameters = array_merge($parameters, $headerParameters);
            }

        }

        return new Request($httpMethod, $httpUrl, $parameters);
    }
569865
public static Set<ApiParamDoc> buildQueryParams(Method method) {
		Set<ApiParamDoc> apiParamDocs = new LinkedHashSet<ApiParamDoc>();
		Class<?> controller = method.getDeclaringClass();

		if (isAnnotated(controller, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(controller, RequestMapping.class);
			addRequestMappingParamDoc(apiParamDocs, requestMapping);
		}

		if (isAnnotated(method, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(method, RequestMapping.class);
			addRequestMappingParamDoc(apiParamDocs, requestMapping);
		}

		Annotation[][] parametersAnnotations = method.getParameterAnnotations();
		for (int i = 0; i < parametersAnnotations.length; i++) {
			RequestParam requestParam = null;
			ModelAttribute modelAttribute = null;
			ApiQueryParam apiQueryParam = null;
			ApiParamDoc apiParamDoc = null;
			
			for (Annotation annotation : parametersAnnotations[i]) {
				if (annotation instanceof RequestParam) {
					requestParam = (RequestParam) annotation;
				}
				if(annotation instanceof ModelAttribute) {
					modelAttribute = (ModelAttribute) annotation;
				}
				if (annotation instanceof ApiQueryParam) {
					apiQueryParam = (ApiQueryParam) annotation;
				}
				
				if (requestParam != null) {
					apiParamDoc = new ApiParamDoc(requestParam.value().isEmpty() ? requestParam.name() : requestParam.value(), "", JSONDocTypeBuilder.build(new JSONDocType(), method.getParameterTypes()[i], method.getGenericParameterTypes()[i]), String.valueOf(requestParam.required()), new String[] {}, null, requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE) ? "" : requestParam.defaultValue());
					mergeApiQueryParamDoc(apiQueryParam, apiParamDoc);
				}
				if(modelAttribute != null) {
					apiParamDoc = new ApiParamDoc(modelAttribute.value(), "", JSONDocTypeBuilder.build(new JSONDocType(), method.getParameterTypes()[i], method.getGenericParameterTypes()[i]), "false", new String[] {}, null, null);
					mergeApiQueryParamDoc(apiQueryParam, apiParamDoc);
				}
				
			}
			
			if(apiParamDoc != null) {
				apiParamDocs.add(apiParamDoc);
			}
		}
		
		return apiParamDocs;
	}
681420
public function setRequestMethods(array $requestMethods) {

	    $requestMethods = array_map('strtoupper', $requestMethods);

        $allowedMethods	= ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];

        foreach($requestMethods as $requestMethod) {
			if(!in_array($requestMethod, $allowedMethods)) {
				throw new \InvalidArgumentException(sprintf("Invalid request method '%s'.", $requestMethod));
			}
		}

		$this->requestMethods = $requestMethods;
		return $this;

	}
1277701
protected String buildQuery(Properties parms, RequestType type) {
    if (parms.isEmpty())
      type = RequestType.query;
    RString result = new RString(_queryHtml);
    result.replace("REQ_NAME", this.getClass().getSimpleName());
    StringBuilder query = new StringBuilder();
    query.append("<form onsubmit='return false;'>");
    RString script = new RString(_queryJs);
    script.replace("REQUEST_NAME", getClass().getSimpleName());
    for (Argument arg: _arguments) {
      try {
        arg.check(RequestQueries.this, parms.getProperty(arg._name,""));
        queryArgumentValueSet(arg, parms);
      } catch( IllegalArgumentException e ) {
        // in query mode only display error for arguments present
        if ((type != RequestType.query) || !parms.getProperty(arg._name,"").isEmpty())
          query.append("<div class='alert alert-error'>"+e.getMessage()+"</div>");
      }
      if (arg._hideInQuery)
        continue;
      if (!arg.disabled()) {
        RString x = script.restartGroup("REQUEST_ELEMENT");
        x.replace("ELEMENT_NAME",arg._name);
        // If some Argument has prerequisites, and those pre-reqs changed on
        // this very page load then we do not assign the arg here: the values
        // passed will be something valid from the PRIOR page - based on the
        // old pre-req - and won't be correct.  Not assigning them here means
        // we'll act "as if" the field was never filled in.
        if( arg._prerequisites != null ) {
          StringBuilder sb = new StringBuilder("if( ");
          ArrayList<RequestArguments.Argument> preqs = arg._prerequisites;
          for( RequestArguments.Argument dep : preqs )
            sb.append("specArg!=='").append(dep._name).append("' && ");
          sb.append("true ) ");
          x.replace("ELEMENT_PREQ",sb);
        }
        x.append();
        x = script.restartGroup("ELEMENT_VALUE");
        x.replace("ELEMENT_NAME",arg._name);
        x.replace("BODY","function query_value_"+arg._name+"() { "+arg.jsValue()+"} ");
        x.append();
      }
      if (arg.refreshOnChange()) {
        RString x = script.restartGroup("ELEMENT_ONCHANGE");
        x.replace("BODY",arg.jsRefresh("query_refresh"));
        x.append();
      }
      RString x = script.restartGroup("ELEMENT_ADDONS");
      x.replace("BODY", arg.jsAddons());
      x.append();
    }
    for(Argument arg:_arguments){
      if (arg._hideInQuery)
        continue;
      query.append(arg.query());
    }
    query.append("</form>");
    result.replace("QUERY",query.toString());
    result.replace("SCRIPT",script.toString());
    return result.toString();
  }

}
816053
static function build($request_name, $params, $helper = NULL) {
    return self::processSchema(self::getRequestSchema($request_name), $params, $helper);
  }