解析RPC请求结果

@param $res

@return bool|null
@throws \Exception
433784
protected function parseRPCResult($res)
    {
        $rpcRes = $res['data'];

        if (!empty($rpcRes['output'])) {
            echo $rpcRes['output'];
        }

        if (!empty($rpcRes['exception'])) {
            $exception = new \Exception($rpcRes['exception']['msg'], $rpcRes['exception']['code']);

            $file = new \ReflectionProperty($exception, 'file');
            $file->setAccessible(true);
            $file->setValue($exception, $rpcRes['exception']['file']);

            $line = new \ReflectionProperty($exception, 'line');
            $line->setAccessible(true);
            $line->setValue($exception, $rpcRes['exception']['line']);

            throw $exception;
        }

        if (isset($rpcRes['status']) && $rpcRes['status'] != 200) {
            return false;
        }

        return isset($rpcRes['return']) ? $rpcRes['return'] : null;
    }
338459
static public function check(FedoraResource $res): bool {
        if (self::$client === null) {
            self::$client = new Client([
                'verify'  => false,
            ]);
        }

        $headers = [];
        if (isset($_SERVER['PHP_AUTH_USER'])) {
            $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
        }
        $cookies = [];
        foreach ($_COOKIE as $k => $v) {
            $cookies[] = $k . '=' . $v;
        }
        if (count($cookies) > 0) {
            $headers['Cookie'] = implode('; ', $cookies);
        }

        $req = new Request('GET', $res->getUri() . '/fcr:metadata', $headers);
        try {
            $resp = self::$client->send($req);
            return true;
        } catch (RequestException $ex) {
            if ($ex->hasResponse()) {
                $resp = $ex->getResponse();
                if (in_array($resp->getStatusCode(), [401, 403])) {
                    return false;
                }
            }
            throw $ex;
        }
    }
853767
public function post($uri, $parameters = [], $headers = [])
    {
        if(in_array($uri, $this->urlSignWithPrivateKeys)) {
            if(empty($this->privateKey)) {
                throw new \RuntimeException('the private key is not set yet');
            }

            if(empty($parameters['sign_type'])) {
                $parameters['sign_type'] = 'RSA';
            }
        }

        $response = $this->guzzle->post($uri, [
            'form_params' => $this->prepareForRequest($parameters),
            'headers' => $headers
        ]);

        $data = json_decode($response->getBody(), true);
        if($data['errcode']) {
            throw new \Exception($data['msg'], $data['errcode']);
        }

        if(!$this->verifyResponse($data)) {
            throw new \Exception('响应签名不正确');
        }

        return $this->decodeData($data['data']);
    }
530106
public function getPermissionStatus(string $role, string $permission, string $resource) : bool
    {
        if (!$this->roleRegistry->exists($role)) {
            throw new \Exception(
                sprintf(
                    "The role: %s doesnt exist",
                    (string)$role
                )
            );
        }

        if (!$this->permissionRegistry->exists($permission)) {
            throw new \Exception(
                sprintf(
                    "The permission: %s doesnt exist",
                    (string)$permission
                )
            );
        }

        if (!$this->resourceRegistry->exists($resource)) {
            throw new \Exception(
                sprintf(
                    "The resource: %s doesnt exist",
                    (string)$resource
                )
            );
        }

        $roleObject = $this->globalRegistry->get($role);

        if (isset($roleObject[$resource][$permission]["status"]))
        {
            return $roleObject[$resource][$permission]["status"];
        }

        $parents = $this->roleRegistry->getRegistry()[$role];

        foreach ($parents as $parentRole)
        {
            $permissionStatus = $this->getPermissionStatus($parentRole, $permission, $resource);

            if ($permissionStatus)
            {
                return true;
            }
        }

        return false;
    }
918248
public function recv()
    {
        _retry_recv:
        if (self::STATUS_WAITING !== $this->_status) {
            throw new BadMethodCallException('You can\'t recv because client is not in waiting stat.');
        }
        $this->client->recv($this->getTimeout());
        $this->_status = self::STATUS_NONE;
        $this->_time = microtime(true) - $this->_start_time;

        $is_report = $this->getExceptionReport() & HttpExceptionMask::E_CONNECT;
        $statusCode = $this->client->statusCode;
        $errCode = $this->client->errCode;
        if ($statusCode < 0 || $errCode !== 0) {
            if ($is_report) {
                if ($statusCode === -1) {
                    $message = 'Connect timeout! the server is not listening on the port or the network is missing!';
                } elseif ($statusCode === -2) {
                    $timeout = $this->getTimeout();
                    $message = "Request timeout! the server hasn't responded over the timeout setting({$timeout}s)!";
                } elseif ($statusCode === -3) {
                    $message = 'Connection is reset by the remote server';
                } else {
                    $message = "Linux Code {$errCode}: " . swoole_strerror($errCode);
                }
                $exception = new ConnectException($this, $statusCode, $message);
                $ret = $this->callInterceptor('exception', $exception);
                if (!$ret) {
                    $this->tryToRevertClientToPool(true);
                    throw $exception;
                }
            } else {
                // Exception is no longer triggered after an exception is ignored
                $this->setExceptionReport(HttpExceptionMask::E_NONE);
            }
        }

        //将服务器cookie添加到客户端cookie列表中去
        if (!empty($this->client->set_cookie_headers)) {
            $domain = $this->uri->getHost();
            //in URI, the path must end with '/', cookie path is just the opposite.
            $path = rtrim($this->uri->getDir(), '/');
            $this->incremental_cookies->adds(
                array_values($this->client->set_cookie_headers), [
                'domain' => $domain,
                'path' => $path,
            ]);
            $this->cookies->adds($this->incremental_cookies); //TODO: optimize
        }

        /** Solve redirect */
        if (($this->client->headers['location'] ?? false) && $this->_redirect_times < $this->redirect) {
            $current_uri = (string)$this->uri;
            //record headers before redirect
            $this->_redirect_headers[$current_uri] = PHP_DEBUG ?
                array_merge([], $this->client->headers) :
                $this->client->headers;
            $location = $this->client->headers['location'];
            $this->uri = Uri::resolve($this->uri, $location);
            if ($this->uri->getPort() === 443) {
                $this->withSSL(true);
            }
            // TODO: remove some secret information
            $this->withMethod('GET')
                ->withBody(null)
                ->withHeader('Host', $this->uri->getHost())
                ->withHeader('Referer', $current_uri)
                ->removeInterceptor('request');

            /**
             * Redirect-interceptors have permission to release or intercept redirects,
             * just return a bool type value
             */
            $allow_redirect = true;
            $ret = $this->callInterceptor('before_redirect', $this);
            if ($ret !== null) {
                if (is_bool($ret)) {
                    $allow_redirect = $ret;
                } else {
                    return $ret;
                }
            }

            if ($allow_redirect) {
                $this->_form_flag |= self::FROM_REDIRECT;
                $this->exec();
                $this->_redirect_times++;

                if ($this->isInQueue()) {
                    return $this;
                }

                return $this->recv();
            } else {
                $this->setExceptionReport(
                    $this->getExceptionReport() ^ HttpExceptionMask::E_REDIRECT
                );
            }
        }

        /** create response object */
        $response = new Response($this);

        /** call response interceptor */
        $ret = $this->callInterceptor('response', $response, $this);
        if ($ret !== null) {
            return $ret;
        }

        /** auto retry */
        while (!$response->getSuccess() && $this->_retried_time++ < $this->retry_time) {
            $ret = $this->callInterceptor('before_retry', $this, $response);
            if ($ret === false) {
                break;
            }
            $this->_form_flag |= self::FROM_RETRY;
            $this->exec();
            if ($this->isInQueue()) {
                return $this;
            } else {
                goto _retry_recv;
            }
        }

        // clear native client
        if (SABER_HCP_NEED_CLEAR) {
            $this->client->headers = [];
            $this->client->set_cookie_headers = [];
            $this->client->cookies = [];
        }
        $this->client->body = '';

        $this->tryToRevertClientToPool();

        return $response;
    }
1278907
public function read($handle)
	{
		if (!is_resource($handle) || get_resource_type($handle) !== 'stream') {
			throw new Exception('Argument must be stream resource.');
		}

		$stat = fstat($handle);

		$sql = '';
		$delimiter = ';';
		$count = $size = 0;

		while (!feof($handle)) {
			$s = fgets($handle);
			$size += strlen($s);
			if (strtoupper(substr($s, 0, 10)) === 'DELIMITER ') {
				$delimiter = trim(substr($s, 10));

			} elseif (substr($ts = rtrim($s), -strlen($delimiter)) === $delimiter) {
				$sql .= substr($ts, 0, -strlen($delimiter));
				if (!$this->connection->query($sql)) {
					throw new Exception($this->connection->error . ': ' . $sql);
				}
				$sql = '';
				$count++;
				if ($this->onProgress) {
					call_user_func($this->onProgress, $count, isset($stat['size']) ? $size * 100 / $stat['size'] : null);
				}

			} else {
				$sql .= $s;
			}
		}

		if (rtrim($sql) !== '') {
			$count++;
			if (!$this->connection->query($sql)) {
				throw new Exception($this->connection->error . ': ' . $sql);
			}
			if ($this->onProgress) {
				call_user_func($this->onProgress, $count, isset($stat['size']) ? 100 : null);
			}
		}

		return $count;
	}
406714
public function send($callback)
    {
        $result = false;
        if ($this->__type === self::READ_FILE) {
            $result = \Swoole\Async::readFile($this->__filename, $callback);
        }
        if ($this->__type === self::WRITE_FILE) {
            $result = \Swoole\Async::writeFile($this->__filename, $this->__content, $callback, $this->__flags);
        }

        if ($result === false) {
            throw new Exception("{$this->__filename} 无法打开，请检查");
        }

        return $this;
    }
686059
function getServer($servers)
    {
        if (empty($servers))
        {
            throw new \Exception("servers config empty.");
        }

        if ($this->keepSocket)
        {
            if (is_array($this->keepSocketServer) && count($this->keepSocketServer))
            {
                return $this->keepSocketServer;
            }
            else
            {
                $this->keepSocketServer = Tool::getServer($servers);

                return $this->keepSocketServer;
            }
        }

        //保留老的server获取方式
        return Tool::getServer($servers);
    }
751627
public function verifyReturn(){
        if(empty($_GET)) {//判断POST来的数组是否为空
            return false;
        }
        else {
            //生成签名结果
            $isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
            //获取支付宝远程服务器ATN结果（验证是否是支付宝发来的消息）
            $responseTxt = 'true';
            if (! empty($_GET["notify_id"])) {$responseTxt = $this->getResponse($_GET["notify_id"]);}

            //写日志记录
            //if ($isSign) {
            //	$isSignStr = 'true';
            //}
            //else {
            //	$isSignStr = 'false';
            //}
            //$log_text = "responseTxt=".$responseTxt."\n return_url_log:isSign=".$isSignStr.",";
            //$log_text = $log_text.createLinkString($_GET);
            //logResult($log_text);

            //验证
            //$responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
            //isSign的结果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
            if (preg_match("/true$/i",$responseTxt) && $isSign) {
                return true;
            } else {
                return false;
            }
        }
    }
764403
static public function openResult($res) {
		if (!is_array($res))
			throw new Exception('Invalid datatype. Array expected!');

		if (isset($res['error']))
			throw new Exception('Server error: '.$res['error']);

		if (!isset($res['result']))
			throw new Exception('Server returned no result.');

		return $res['result'];
	}
397243
protected static function decodeBody(array $res)
    {
        $format = isset($res['headers']['x-datasift-format'])
            ? $res['headers']['x-datasift-format']
            : $res['headers']['content-type'];
        $retval = array();

        if (strtolower($format) == 'json_new_line') {
            foreach (explode("\n", $res['body']) as $json_string) {
                $retval[] = json_decode($json_string, true);
            }
        } else {
            $retval = json_decode($res['body'], true);
        }

        return $retval;
    }
912376
public function create($resource)
    {
        $className = $this->getResourceClassName($resource->type);
        if (!class_exists($className)) {
            throw new Exception(
                'Unknown resource type "' . $resource->type . '".',
                Exception::UNKNOWN_RESOURCE_TYPE
            );
        }

        /** @var AbstractResource $object */
        $object = $this->objectManager->get($className);

        foreach ($resource as $property => $value) {
            if (!ObjectAccess::isPropertySettable($object, $property)) {
                continue;
            }
            ObjectAccess::setProperty($object, $property, $value);
        }

        $this->postProcessResources($object);

        return $object;
    }
502361
public static function loadKeyFromX509Resource($res)
    {
        $key = openssl_get_publickey($res);

        $details = openssl_pkey_get_details($key);
        if (isset($details['key'])) {
            $values = self::loadKeyFromPEM($details['key']);
            openssl_x509_export($res, $out);
            $values['x5c'] = [trim(preg_replace('#-.*-#', '', $out))];

            if (function_exists('openssl_x509_fingerprint')) {
                $values['x5t'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha1', true));
                $values['x5t#256'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha256', true));
            } else {
                openssl_x509_export($res, $pem);
                $values['x5t'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha1', true));
                $values['x5t#256'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha256', true));
            }

            return $values;
        }

        throw new \InvalidArgumentException('Unable to load the certificate');
    }
442869
public function verify()
    {
        $data = file_get_contents("php://input");
        $data = Xml::xmlToArr($data);
        if ($data['sign'] != Helper::signature($data, Datasheet::get('md5_key'))) {
            throw new \Exception('微信异步通信签名验证失败');
        }
        return $data;
    }
67110
public function rset()
    {
        if (PEAR::isError($error = $this->put('RSET'))) {
            return $error;
        }
        if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
            return $error;
        }

        return true;
    }
434882
public function goGet($url = '', $query = null, $timeout = 30000, $headers = [])
    {
        if (!($this->client instanceof \swoole_http_client)) {
            throw new Exception('You must complete the DNS query first, Such as $client->goDnsLookup()');
        }

        if (empty($this->urlData)) {
            $this->urlData = self::parseUrl($url);
        } else {
            if (!empty($url)) {
                $this->urlData['path'] = $url;
            }
        }
        $this->setHeaders($headers);

        //支持直接在url之后带参数形式的GET请求
        $q = '';
        if (!empty($this->urlData['query'])) {
            $q = ltrim($this->urlData['query'], '?');
        }

        if (!empty($query)) {
            $q .= (empty($q) ? '' : '&') . http_build_query($query) ;
        }

        $sendGetReq  = $this->getObject(Http::class, [$this, 'GET', $this->urlData['path'], $q, $timeout]);

        return $sendGetReq;
    }
831254
public function select($index = 0) {

        $index = intval($index);

        if (isset($this->pool['master']) && !is_null($this->pool['master'])) {
            $res = $this->pool['master']->getHandler()->select($index);
            if (!$res) {
                throw new Exception('change selected database failed');
            }
        }

        if (isset($this->pool['slave']) && !is_null($this->pool['slave'])) {
            $res = $this->pool['slave']->getHandler()->select($index);
            if (!$res) {
                throw new Exception('change selected database failed');
            }
        }

        // 记录当前redis db
        $this->currentDb = $index;
    }