Manipulate on CLI Request
eg CLI Request:
php (args[0])filename.php (args[1])/path/ (args[2])POST (args[3])httpquery=query&query2=valuequery2

@param array $globals

@return array
332552
protected static function manipulateIfCLIRequest(array $globals) : array
    {
        if (php_sapi_name() !== 'cli') {
            return $globals;
        }

        global $argv;
        $args = $argv;
        !isset($args[1]) && $args[1] = '/';
        $args[1] = substr($args[1], 0, 1) !== '/'
            ? '/'. $args[1]
            : $args[1];
        $query_string = explode('?', $args[1]);
        array_shift($query_string);
        $query_string = implode('?', $query_string);

        !isset($args[2]) && $args[2] = 'GET';
        !isset($args[3]) && $args[3] = '';

        if (!isset($globals['REQUEST_URI'])) {
            $globals['REQUEST_URI'] = $args[1];
        }
        if (!isset($globals['QUERY_STRING'])) {
            $globals['QUERY_STRING'] = $query_string;
        }
        if (!isset($globals['HTTP_HOST'])) {
            $globals['HTTP_HOST'] = 'cli';
        }
        if (!isset($globals['REQUEST_METHOD'])) {
            $globals['REQUEST_METHOD'] = $args[2];
        }
        if ($args[3] !== '') {
            file_put_contents('php://input', $args[3]);
        }

        return $globals;
    }
580065
protected function resolveParameters(array $get = [], array $globals = [])
    {
        if ($this->method() != 'CLI' || !isset($globals['argc'], $globals['argv']) || $globals['argc'] <= 1) {
            return $get;
        }

        $cli = [];
        for ($i = 1; $i < $globals['argc']; $i++) {
            if (preg_match_all('/^-+([^=]+)(=(.+))?$/i', $globals['argv'][$i], $arg, PREG_SET_ORDER)) {
                $cli[$arg[0][1]] = isset($arg[0][3]) ? $this->unquote($arg[0][3]) : true;
            } else {
                $cli[] = $this->unquote($globals['argv'][$i]);
            }
        }

        $this->path = array_shift($cli);

        return array_merge($get, $cli);
    }
288266
public static function options( $name = '', $value = '' ) {

		if ( ! empty( $value ) ) {
			$GLOBALS['_OPTIONS'][ $name ] = $value;
		}

		if ( empty( $name ) ) {
			return ( isset( $GLOBALS['_OPTIONS'] ) ) ? $GLOBALS['_OPTIONS'] : NULL;
		} else {
			return ( isset( $GLOBALS['_OPTIONS'][ $name ] ) ) ? $GLOBALS['_OPTIONS'][ $value ] : NULL;
		}

	}
885692
public static function open($params = array()) {

        if( !is_array($params) )
        {
            throw new \InvalidArgumentException("Arguments is not a Array". print_r($params, true));
        }
        $o = '<form';
        $o .= (isset($params['id'])) ? " id='{$params['id']}'" : '';
        $o .= (isset($params['name'])) ? " name='{$params['name']}'" : '';
        $o .= (isset($params['class'])) ? " class='{$params['class']}'" : '';
        $o .= (isset($params['onsubmit'])) ? " onsubmit='{$params['onsubmit']}'" : '';
        $o .= (isset($params['method'])) ? " method='{$params['method']}'" : ' method="get"';
        $o .= (isset($params['action'])) ? " action='{$params['action']}'" : '';
        $o .= (isset($params['files'])) ? " enctype='multipart/form-data'" : '';
        $o .= (isset($params['style'])) ? " style='{$params['style']}'" : '';
        $o .= (isset($params['role'])) ? " role='{$params['role']}'" : '';
        $o .= (isset($params['autocomplete'])) ? " autocomplete='{$params['autocomplete']}'" : '';
        $o .= '>';
        return $o . "\n";
    }
252641
public function processExtensionGlobals($namespace)
    {
        $globalCode = '';
        $globalStruct = '';
        $globalsDefault = [[], []];
        $initEntries = [];

        /**
         * Generate the extensions globals declaration.
         */
        $globals = $this->config->get('globals');
        if (\is_array($globals)) {
            $structures = [];
            $variables = [];
            foreach ($globals as $name => $global) {
                $parts = explode('.', $name);
                if (isset($parts[1])) {
                    $structures[$parts[0]][$parts[1]] = $global;
                } else {
                    $variables[$parts[0]] = $global;
                }
            }

            /*
             * Process compound structures
             */
            foreach ($structures as $structureName => $internalStructure) {
                if (preg_match('/^[0-9a-zA-Z\_]$/', $structureName)) {
                    throw new Exception("Struct name: '".$structureName."' contains invalid characters");
                }

                $structBuilder = new Code\Builder\Struct('_zephir_struct_'.$structureName, $structureName);
                foreach ($internalStructure as $field => $global) {
                    if (preg_match('/^[0-9a-zA-Z\_]$/', $field)) {
                        throw new Exception("Struct field name: '".$field."' contains invalid characters");
                    }

                    $structBuilder->addProperty($field, $global);

                    $isModuleGlobal = (int) !empty($global['module']);
                    $globalsDefault[$isModuleGlobal][] = $structBuilder->getCDefault($field, $global, $namespace).PHP_EOL;
                    $initEntries[] = $structBuilder->getInitEntry($field, $global, $namespace);
                }

                $globalStruct .= $structBuilder.PHP_EOL;
            }

            $globalCode = PHP_EOL;
            foreach ($structures as $structureName => $internalStructure) {
                $globalCode .= "\t".'zephir_struct_'.$structureName.' '.
                                $structureName.';'.PHP_EOL.PHP_EOL;
            }
            /*
             * Process single variables
             */
            foreach ($variables as $name => $global) {
                if (preg_match('/^[0-9a-zA-Z\_]$/', $name)) {
                    throw new Exception("Extension global variable name: '".$name."' contains invalid characters");
                }

                if (!isset($global['default'])) {
                    throw new Exception("Extension global variable name: '".$name."' contains invalid characters");
                }

                $isModuleGlobal = (int) !empty($global['module']);
                $type = $global['type'];
                // @todo Add support for 'string', 'hash'
                // @todo Zephir\Optimizers\FunctionCall\GlobalsSetOptimizer
                switch ($global['type']) {
                    case 'boolean':
                    case 'bool':
                        $type = 'zend_bool';
                        if (true === $global['default']) {
                            $globalsDefault[$isModuleGlobal][] = "\t".$namespace.'_globals->'.$name.' = 1;'.PHP_EOL;
                        } else {
                            $globalsDefault[$isModuleGlobal][] = "\t".$namespace.'_globals->'.$name.' = 0;'.PHP_EOL;
                        }
                        break;

                    case 'int':
                    case 'uint':
                    case 'long':
                    case 'double':
                        $globalsDefault[$isModuleGlobal][]
                            = "\t".$namespace.'_globals->'.$name.' = '.
                            $global['default'].';'.PHP_EOL;
                        break;

                    case 'char':
                    case 'uchar':
                        $globalsDefault[$isModuleGlobal][]
                            = "\t".$namespace.'_globals->'.$name.' = \''.
                            $global['default'].'\';'.PHP_EOL;
                        break;
                    default:
                        throw new Exception(
                            "Unknown type '".$global['type']."' for extension global '".$name."'"
                        );
                }

                $globalCode .= "\t".$type.' '.$name.';'.PHP_EOL.PHP_EOL;
                $iniEntry = [];
                if (isset($global['ini-entry'])) {
                    $iniEntry = $global['ini-entry'];
                }

                if (!isset($iniEntry['name'])) {
                    $iniName = $namespace.'.'.$name;
                } else {
                    $iniName = $iniEntry['name'];
                }

                if (!isset($iniEntry['scope'])) {
                    $scope = 'PHP_INI_ALL';
                } else {
                    $scope = $iniEntry['scope'];
                }

                switch ($global['type']) {
                    case 'boolean':
                    case 'bool':
                        $initEntries[] =
                        'STD_PHP_INI_BOOLEAN("'.
                        $iniName.
                        '", "'.
                        (int) (true === $global['default']).
                        '", '.
                        $scope.
                        ', OnUpdateBool, '.
                        $name.
                        ', zend_'.
                        $namespace.
                        '_globals, '.
                        $namespace.'_globals)';
                        break;
                }
            }
        }
        $globalsDefault[0] = implode('', $globalsDefault[0]);
        $globalsDefault[1] = implode('', $globalsDefault[1]);

        return [$globalCode, $globalStruct, $globalsDefault, $initEntries];
    }
307234
public static function fromGlobals(
        array $server = null,
        array $query = null,
        array $body = null,
        array $cookies = null,
        array $files = null
    ) {
        $cookies = new CookieJar($cookies ?: $_COOKIE);
        $server = static::normalizeServer($server ?: $_SERVER);
        $files = static::normalizeFiles($files ?: $_FILES);
        $headers = static::marshalHeaders($server);
        $request = new Request(
            $cookies,
            $server,
            $files,
            static::marshalUriFromServer($server, $headers),
            static::get('REQUEST_METHOD', $server, 'GET'),
            'php://input',
            $headers
        );

        return $request
            ->withQueryParams($query ?: $_GET)
            ->withParsedBody($body ?: $_POST);
    }
1040046
private function loadGlobalVar(string $name, string $source = ''): array
    {
        $encode = false;

        switch ($name) {
            case 'GET':
                $source = $_SERVER['QUERY_STRING'] ?? '';
                $encode = true;
                break;
            case 'POST': // pass
                break;
            case 'COOKIE':
                if (isset($_SERVER['HTTP_COOKIE'])) {
                    $source = implode('&', array_map('trim', explode(';', $_SERVER['HTTP_COOKIE'])));
                }
                break;
        }

        return Util::parseQueryString($source, $encode);
    }
1000128
public function processImportedSheets(array $data, array $globals) : array {
		$result = [
			'success' => false,
			'error' => [],
			'data' => []
		];
		// process globals
		$globals_final = [];
		$ignore_columns = [];
		if ($this->collection_object->primary_model->tenant) {
			$globals_final[$this->collection_object->primary_model->tenant_column] = $globals[$this->collection_object->primary_model->tenant_column];
			$ignore_columns[$this->collection_object->primary_model->tenant_column] = $this->collection_object->primary_model->tenant_column;
		}
		if ($this->collection_object->primary_model->module) {
			$globals_final[$this->collection_object->primary_model->module_column] = $globals[$this->collection_object->primary_model->module_column];
			$ignore_columns[$this->collection_object->primary_model->module_column] = $this->collection_object->primary_model->module_column;
		}
		// find main sheet
		$main_sheet_data = $data[$this->collection['name']] ?? $data['Main Sheet'] ?? [];
		unset($data[$this->collection['name']], $data['Main Sheet']);
		if (empty($main_sheet_data)) {
			$result['error'][] = \Object\Content\Messages::NO_ROWS_FOUND;
			return $result;
		}
		// loop though header rows
		foreach ($main_sheet_data as $k => $v) {
			$v = array_merge_hard($v, $globals_final);
			// details
			if (!empty($this->collection['details'])) {
				foreach ($this->collection['details'] as $k2 => $v2) {
					$v[$k2] = [];
					if (empty($data[$v2['name']])) continue;
					// go through data
					foreach ($data[$v2['name']] as $k3 => $v3) {
						// map child to parent
						$found = true;
						foreach ($v2['map'] as $k4 => $v4) {
							// important to add new items to ignore columns array
							if (isset($ignore_columns[$k4])) {
								$ignore_columns[$v4] = $v4;
								continue;
							}
							// compare
							if ($v3[$v4] != $v[$k4]) $found = false;
						}
						// if found
						if ($found) {
							// todo process subdetails
							$v[$k2][] = $v3;
							unset($data[$v2['name']][$k3]);
						}
					}
				}
			}
			$result['data'][$k] = $v;
			unset($main_sheet_data[$k]);
		}
		$result['success'] = true;
		return $result;
	}
193365
public function update( array $args ) {

		/** @var array $EZSQL_ERROR */
		global $EZSQL_ERROR;
		if ( empty( $EZSQL_ERROR ) ) {
			return new NullLog();
		}

		$errors  = $EZSQL_ERROR;
		$last    = end( $errors );
		$context = [ 'last_query' => $last[ 'query' ], 'errors' => $errors, ];

		return new Error( $last[ 'error_str' ], Channels::DB, $context );
	}
1068000
public static function fromGlobals()
    {
        $request = new self();

        foreach ([
            'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language',
            'Connection', 'Host', 'Referer', 'User-Agent'
        ] as $name) {
            $key = 'HTTP_' . str_replace('-', '_', strtoupper($name));
            if (isset($_SERVER[$key])) {
                $request->setHeader($name, $_SERVER[$key], false);
            }
        }

        $request->_isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off');

        $request->_method = $_SERVER['REQUEST_METHOD'];
        $request->_uri = $_SERVER['REQUEST_URI'];

        $request->_path = strstr($_SERVER['REQUEST_URI'], '?', true);
        if ($request->_path == false) {
            $request->_path = $_SERVER['REQUEST_URI'];
        }
        $request->_query = strstr($_SERVER['REQUEST_URI'], '?');
        if ($request->_query == false) {
            $request->_query = '';
        }

        return $request;
    }
21663
public function group($scopes, $global = true)
    {
        $groups = array(
          'posts' => array(),
          'actors' => array(),
          'other' => array()
        );

        $current = $this->_template->getView()->current_scope;

        foreach ($scopes as $scope) {
          if ($scope->type == 'post') {
              $groups['posts'][] = $scope;
          } elseif($scope->type == 'actor' && $global) {
              $groups['actors'][] = $scope;
          }
        }

        return $groups;
    }
190211
public function createRequestFromArray(array $headers): GenericRequest
    {
        $upperCaseHeaders = [];

        foreach ($headers as $header => $value) {
            $upperCaseHeader = mb_strtoupper(str_replace('-', '_', $header));

            if (0 !== mb_strpos($upperCaseHeader, 'HTTP_')) {
                $upperCaseHeader = 'HTTP_' . $upperCaseHeader;
            }

            if (!HeaderSecurity::isValid($value)) {
                $value = $this->filterHeader($value);
            }

            $upperCaseHeaders[$upperCaseHeader] = $value;
        }

        $message = ServerRequestFactory::fromGlobals($upperCaseHeaders);

        return $this->createRequestFromPsr7Message($message);
    }
1184419
private function getCLIGlobalOptions()
    {
        $command = '';
        if (count($this->globalOptions) > 0) {
            foreach ($this->globalOptions as $name => $value) {
                $command .= sprintf(' %s=%s', escapeshellarg($name), escapeshellarg($value));
            }
        }
        return $command;
    }
932504
public function call($path = '', $params = [])
    {
        $default_params = [
            'api_token' => $this->getGuzzleClient()->getConfig('api_token'),
            'aid' => $this->getGuzzleClient()->getConfig('aid'),
        ];

        $params = array_merge($default_params, $params);

        if ($this->getGuzzleClient()->getConfig('method') === 'post') {
            $response = $this->getGuzzleClient()->post('/api/v3' . $path, [
                'verify' => false,
                'form_params' => $params,
            ]);
        } else {
            $response = $this->getGuzzleClient()->get('/api/v3' . $path, [
                'verify' => false,
                'query' => $params,
            ]);
        }
        $data = json_decode($response->getBody()->getContents());

        switch ($data->code) {
            case 401:
            case 404:
                throw new HttpRequestException($data->message);
                break;
            case 400:
            case 805:
            case 5001:
            case 5003:
                throw new InvalidArgumentException($data->message);
                break;
        }

        return $data;
    }
30010
public function parse($arguments = null)
    {
        $this->_options = [];
        $this->_values = [];

        if ($arguments === null) {
            if (isset($GLOBALS['argv'][1]) && $GLOBALS['argv'][1][0] === '/') {
                $arguments = [$GLOBALS['argv'][1]];
            } else {
                /** @noinspection CallableParameterUseCaseInTypeContextInspection */
                $arguments = array_slice($GLOBALS['argv'], 3);
            }
        }

        if (count($arguments) === 1 && $arguments[0][0] === '/') {
            $query = parse_url($arguments[0], PHP_URL_QUERY);
            parse_str($query, $this->_options);
            if (($fragment = parse_url($arguments[0], PHP_URL_FRAGMENT)) !== null) {
                $this->_values[] = $fragment;
            }
        } else {
            $this->_parse($arguments);
        }

        return $this;
    }
998982
protected function resolveRequest($args)
	{
		$options=array();	// named parameters
		$params=array();	// unnamed parameters
		foreach($args as $arg)
		{
			if(preg_match('/^--(\w+)(=(.*))?$/',$arg,$matches))  // an option
			{
				$name=$matches[1];
				$value=isset($matches[3]) ? $matches[3] : true;
				if(isset($options[$name]))
				{
					if(!is_array($options[$name]))
						$options[$name]=array($options[$name]);
					$options[$name][]=$value;
				}
				else
					$options[$name]=$value;
			}
			elseif(isset($action))
				$params[]=$arg;
			else
				$action=$arg;
		}
		if(!isset($action))
			$action=$this->defaultAction;

		return array($action,$options,$params);
	}
714273
protected function parseConnectionParams($params, $defaults = [])
    {
        // Handle host shortcut
        if (is_string($params)) {
            $params = ['host' => $params];
        }

        // Convert keys from Bolt
        $replacements = [
            'databasename' => 'dbname',
            'username'     => 'user',
        ];
        foreach ($replacements as $old => $new) {
            if (isset($params[$old])) {
                $params[$new] = $params[$old];
                unset($params[$old]);
            }
        }

        // Merge in defaults
        $params = array_replace($defaults, $params);

        // Filter out invalid keys
        $validKeys = [
            'user', 'password', 'host', 'port', 'dbname', 'charset',      // common
            'path', 'memory',                                             // Qqlite
            'unix_socket', 'driverOptions', 'collate',                    // MySql
            'sslmode',                                                    // PostgreSQL
            'servicename', 'service', 'pooled', 'instancename', 'server', // Oracle
            'persistent',                                                 // SQL Anywhere
        ];
        $params = array_intersect_key($params, array_flip($validKeys));

        return $params;
    }