处理api请求路由

@throws \Exception \PDOException logicException

@return void
543154
private function routeApi()
    {
        // get protocol class
        if ($this->apiProtocolClass != "framework\\protocol\\Api") {
            try {
                $api_protocol_class = sprintf("main\\%s\\protocol\\%s", $this->currentApp, $this->apiProtocolClass);
                if (!class_exists($api_protocol_class)) {
                    throw new HornetCoreException($api_protocol_class . ' no found', 500);
                }
            } catch (HornetCoreException $exception) {
                $apiProtocol = new Api($this->enableTrace);
                $this->handleApiException($apiProtocol, $exception);
                return;
            }
            $apiProtocol = new $api_protocol_class($this->enableTrace);
        } else {
            $apiProtocol = new Api($this->enableTrace);
        }

        // url route to controller
        try {
            // sql注入检查
            if ($this->enableFilterSqlInject) {
                $filterSqlInject = new FilterSqlInject($this->storagePath . '/log/sql_inject/');
                $filterSqlInject->filterInput();
            }
            if (!strpos($this->cmd, '.')) {
                throw new \Exception('Api invoker error: cmd param error!', 500);
            }
            list ($service, $method) = explode('.', $this->cmd);
            $service = ucfirst($service);
            $service = $this->underlineToUppercase($service);
            $serviceClass = sprintf("main\\%s\\api\\%s", $this->currentApp, $service);
            if (!empty($this->mod) && $this->mod != 'api') {
                $serviceClass = sprintf("main\\%s\\api\\%s\\%s", $this->currentApp, $this->mod, $service);
            }

            $service_obj = new $serviceClass();

            if (!method_exists($service_obj, $method)) {
                $method = $this->underlineToUppercase($method);
                if (!method_exists($service_obj, $method)) {
                    throw new \Exception($this->ctrl . '->' . $method . ' no found;', 404);
                }
            }

            // 安全映射机制
            $this->securityMapCheck($this->modApiName, $service, $method);

            if (($this->appStatus == 'development' || $this->appStatus == 'test') && $this->enableWriteReqLog) {
                $reqLogPath = $this->storagePath . 'tmp/' . date('Y-m-d') . '_request.log';
                $dateTime = date('H:i:s');
                $getStr = var_export($_GET, true);
                $postStr = var_export($_POST, true);
                $cookieStr = var_export($_COOKIE, true);
                $logContent = $dateTime . ': ' . $getStr . $postStr . $cookieStr . "\n\n";
                f($reqLogPath, $logContent, FILE_APPEND);
                unset($dateTime, $getStr, $postStr, $cookieStr, $logContent);
            }
            $reflectMethod = null;
            // 通过反射获取调用方法的参数列表
            if ($this->enableReflectMethod) {
                $reflectMethod = new \ReflectionMethod($service_obj, $method);
                $args = [];
                $defaults = [];
                foreach ($reflectMethod->getParameters() as $param) {
                    $args[] = $param->getName();
                    $defaults[] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
                }
                if (empty($args)) {
                    // 开始执行业务逻辑流程
                    $result = call_user_func_array([$service_obj, $method], []);
                } else {
                    $params = array();
                    foreach ($args as $ak => $arg) {
                        $params[$ak] = isset($_REQUEST[$arg]) ? $_REQUEST[$arg] : $defaults[$ak];
                    }
                    // 开始执行业务逻辑流程
                    $result = call_user_func_array([$service_obj, $method], $params);
                }
            } else {
                $result = call_user_func_array([$service_obj, $method], []);
            }

            // 执行结束检验结果类型
            $apiProtocol->builder('200', $result, '', $this->format);
            $jsonStr = $apiProtocol->getResponse();
            if ($this->format == 'json' && $this->enableReflectMethod) {
                $return_obj = json_decode(json_encode($result));
                $this->validReturnJson($reflectMethod, $apiProtocol, $return_obj, $jsonStr);
            }
            echo $jsonStr;
            if (($this->appStatus == 'development' || $this->appStatus == 'test') && $this->enableWriteReqLog) {
                $reqLogPath = $this->storagePath . 'tmp/' . date('Y-m-d') . '_request.log';
                $datetime = date('H:i:s');
                $getStr = var_export($_GET, true);
                $postStr = var_export($_POST, true);
                $cookieStr = var_export($_COOKIE, true);
                $logContent = $datetime . ': ' . $getStr . $postStr . $cookieStr . "\n\n";
                unset($datetime, $getStr, $postStr, $cookieStr);
                f($reqLogPath, $logContent, FILE_APPEND);
            }
            closeResources();
        } catch (HornetCoreException  $e) {
            $this->handleApiException($apiProtocol, $e);
        } catch (HornetLogicException  $e) {
            $this->handleApiException($apiProtocol, $e);
        } catch (\PDOException $e) {
            $this->handleApiException($apiProtocol, $e);
        } catch (\Exception $e) {
            $this->handleApiException($apiProtocol, $e);
        }
    }
1038154
public function delete()
    {

        //没有设置条件不能删除
        if ($this->condition->count() < 1) {
            throw new BaseException(QueryException::DELETE_NOT_WHERE);
        }
        $whereStr       = (string)$this->condition->compile();
        $whereArguments = $this->condition->arguments();
        $sql            = "DELETE FROM {$this->getFrom()} WHERE ".$whereStr;
        return $this->connection->executeUpdate($sql, $whereArguments);
    }
427770
public function execute()
    {
        try {
            $opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
            $pdo  = new PDO('mysql:host=' . $this->host, $this->user, $this->pass, $opts);

            foreach ($this->queries as $query) {
                if (!is_array($query)) {
                    // Simple query
                    $pdo->query($this->phpci->interpolate($query));
                } elseif (isset($query['import'])) {
                    // SQL file execution
                    $this->executeFile($query['import']);
                } else {
                    throw new \Exception(Lang::get('invalid_command'));
                }
            }
        } catch (\Exception $ex) {
            $this->phpci->logFailure($ex->getMessage());
            return false;
        }
        return true;
    }
1193376
public function beforeCompile()
	{
		$builder = $this->getContainerBuilder();

		if (!$builder->getByType(Application::class)) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', Application::class));
		}

		if (!$builder->getByType(EventDispatcher::class)) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', EventDispatcher::class));
		}

		$application = $builder->getDefinition($builder->getByType(Application::class));
		$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcher::class));

		$application->addSetup('?->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_STARTUP,
			new PhpLiteral(StartupEvent::class),
		]);
		$application->addSetup('?->onError[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_ERROR,
			new PhpLiteral(ErrorEvent::class),
		]);
		$application->addSetup('?->onPresenter[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER,
			new PhpLiteral(PresenterEvent::class),
		]);
		$application->addSetup('?->onRequest[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_REQUEST,
			new PhpLiteral(RequestEvent::class),
		]);
		$application->addSetup('?->onResponse[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_RESPONSE,
			new PhpLiteral(ResponseEvent::class),
		]);
		$application->addSetup('?->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_SHUTDOWN,
			new PhpLiteral(ShutdownEvent::class),
		]);
	}
55216
public function getError() {
        if ($this->PDOStatement) {
            $error = $this->PDOStatement->errorInfo();
            $error = $error[ 1 ] . ':' . $error[ 2 ];
        } else {
            $error = '';
        }
        if ('' != $this->queryStr) {
            $error .= "\n [ SQL语句 ] : " . $this->queryStr;
        }
        return $error;
    }
818678
public function execute() {
		
		// build the query
		$this->buildQuery();

		// prepare the statement
		$this->Prepared = \Polyfony\Database::handle()->prepare($this->Query);
		
		// marker start (after preparation, otherwise we would not be able to read the query, it wouldn't exist yet!)
		$id_marker = Profiler::setMarker(null, 'database', ['Query'=>$this]);

		// if prepare failed
		if(!$this->Prepared) {
			// throw an exception
			$this->throwExceptionOn('prepare');
		}
		
		// execute the statement
		$this->Success = $this->Prepared->execute($this->Values);
		
		// if execution failed
		if($this->Success === false) {
			// throw an exception
			$this->throwExceptionOn('execute');
		}

		// if a forced type of object has been defined
		$this->Object = $this->Object && $this->Object != 'Record' ? 
			'\Models\\'.$this->Object : 
			'\Models\\'.$this->Table;

		// temporary fix, if we don't have an object class at all
		if($this->Object == '\Models\\') {
			$this->Object = '\Polyfony\\Record';
		}

		// tweak for Microsoft SQL Server and MySQL
		$this->Object = str_replace('"','', $this->Object);
		
		// fetch all results as objects
		$this->Result = $this->Prepared->fetchAll(PDO::FETCH_CLASS, $this->Object);

		// format the result
		$this->formatSelectResult();
		$this->formatUpdateOrDeleteResult();
		$this->formatInsertResult();

		// marker end, release after all manipulation has been done
		Profiler::releaseMarker($id_marker);

		// return whatever result we got
		return $this->Result;
	}
86196
public function start()
    {
        $cmd = $this->command->getPreparedCommand();
        $cwd = realpath(CRAFT_BASE_PATH);

        $process = Process::fromShellCommandline($cmd, $cwd);

        try {
            $process->run();
        } catch (\Symfony\Component\Process\Exception\RuntimeException $e) {
            $e = new RuntimeException($e->getMessage());
            $e->setProcess($process);
            throw $e;
        } catch (\Symfony\Component\Process\Exception\LogicException $e) {
            $e = new LogicException($e->getMessage());
            $e->setProcess($process);
            throw $e;
        }

        return $process;
    }
412479
protected function login()
    {
        if ($this->hostFingerprint) {
            $publicKey = $this->connection->getServerPublicHostKey();

            if ($publicKey === false) {
                throw new LogicException('Could not connect to server to verify public key.');
            }

            $actualFingerprint = $this->getHexFingerprintFromSshPublicKey($publicKey);

            if (0 !== strcasecmp($this->hostFingerprint, $actualFingerprint)) {
                throw new LogicException('The authenticity of host '.$this->host.' can\'t be established.');
            }
        }

        $authentication = $this->getAuthentication();

        if (! $this->connection->login($this->getUsername(), $authentication)) {
            throw new LogicException('Could not login with username: '.$this->getUsername().', host: '.$this->host);
        }

        if ($authentication instanceof Agent) {
            $authentication->startSSHForwarding($this->connection);
        }
    }
256093
public function insert()
    {
        if( !$this->tableName ) {
            throw new LogicException('No table name specified');
        }
        return $this->database->insert()
                ->table($this->tableName);
    }
877128
public static function run()
    {
        try {

            self::init();

            // 设置系统时区
            date_default_timezone_set(self::$config['default_timezone']);

            // 是否开启debug
            self::$debug = self::$config['app_debug'];

            // 初始化路由
            Route::init();

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        return self::$config;
    }
784172
public function refer()
    {
        if ($this->context == null) {
            throw new LogicException('Context must be set before refer to the service.');
        }

        if ($this->proxyFactory == null) {
            throw new LogicException('Proxy factory must be set before refer to the service.');
        }

        if ($this->clientFactory == null) {
            throw new LogicException('Client factory must be set before refer to the service.');
        }

        $identify = $this->config['id'] ?? $this->config['interface'] ?? null;

        $this->container->instance($identify, $this->getProxy());
    }
965827
protected function initializable()
    {
        if (!$this->getParamAdapter()) {
            throw new Exception\LogicException('Param Adapter is required');
        }

        if (!$this->getSource()) {
            throw new Exception\LogicException('Source data is required');
        }

        $this->init = true;

        if (count($this->headers)) {
            $this->setHeaders($this->headers);
        }

        $this->init();

        $this->initFilters($this->getSource()->getSource());
    }
140376
public static function init()
  {
    if(version_compare(phpversion(), "5.2.1") == -1)
    {
      throw new LogicException("this particular software cannot be used with the installed version of PHP");
    }

    if(!function_exists("stream_socket_client"))
    {
      throw new LogicException("network functions are not available in this PHP installation");
    }

    if(!function_exists("spl_autoload_register"))
    {
      throw new LogicException("autoload functions are not available in this PHP installation");
    }

    if(!class_exists("TeamSpeak3_Helper_Profiler"))
    {
      spl_autoload_register(array(__CLASS__, "autoload"));
    }

    TeamSpeak3_Helper_Profiler::start();
  }
110608
public function connection()
    {
        try {
            $this->_instances = new PDO($this->params['dns'], $this->params['users'], $this->params['pass'],
                    [\PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8']);

            $attributes = array(
                    'AUTOCOMMIT', 'ERRMODE', 'CASE', 'CLIENT_VERSION', 'CONNECTION_STATUS',
                    'ORACLE_NULLS', 'PERSISTENT', 'SERVER_INFO', 'SERVER_VERSION',
                );
            foreach ($attributes as $value) {
                $this->_instances->getAttribute(constant("PDO::ATTR_$value"))."\n";
            }
        } catch (\PDOException $exc) {
            throw new \Exception('Failed to connect to database. Reason: '.$exc->getMessage());
        }

        return $this->_instances;
    }
1338959
public function getQuery()
    {
        switch ($this->queryClass) {
            case DeleteItem::class:
                return $this->makeDelete();
            case GetItem::class:
                return $this->makeGet();
            case PutItem::class:
                return $this->makePut();
            case Scan::class:
                return $this->makeScan();
            case UpdateItem::class:
                return $this->makeUpdate();
            case Query::class:
                return $this->makeQuery();
        }

        throw new \LogicException;
    }
209726
public function fetch()
        {
            try {
                if ($this->values = $this->statement->fetch(\PDO::FETCH_ASSOC)) {
                    return $this->values;
                } else {
                    return false;
                }
            } catch (\PDOException $e) {
                throw new Exception('An error occured while trying to fetch the result: "' . $e->getMessage() . '"');
            }
        }
602342
public function init() {
        if (VERBOSE) echo 'INIT:' ,PHP_EOL;
        if (VERBOSE) echo ' CONNECTING API' ,PHP_EOL;
        $this->api->auth();
        if (VERBOSE) echo ' API CONNECTED' ,PHP_EOL;
        if (VERBOSE) echo ' CONNECTING SQL' ,PHP_EOL;
        $this->db->connect();
        if (VERBOSE) echo ' SQL CONNECTED' ,PHP_EOL;
        if (VERBOSE) echo ' CHECKING PATHS' ,PHP_EOL;
        if (DEBUG) echo '  CHECKING TMP DIR AT : '.$this->tmp_dir ,PHP_EOL;
        if (!file_exists($this->tmp_dir)) {
            throw new Exception("Path for 'tmp_dir' not found at '".$this->tmp_dir."'!");
        }
        if (DEBUG) echo '  CHECKING DUMP DIR AT : '.$this->dumps_dir ,PHP_EOL;
        if (!file_exists($this->dumps_dir)) {
            throw new Exception("Path for 'dumps_dir' not found at '".$this->dumps_dir."'!");
        }
        if (VERBOSE) echo ' PATHS FOUND' ,PHP_EOL;
    }