Write request to stream

@param  array $args
514579
private function request_write($args)
    {
        $request = json_encode($args)."\n";
        $this->last_request = $request;
        if (!$this->stream) {
            $desc = $this->request_description();
            throw new NetworkException("Unable to execute request ({$desc}): Connection closed");
        }

        // Must block while writing
        stream_set_blocking($this->stream, true);

        for ($written = 0; $written < strlen($request); $written += $fwrite) {
            $fwrite = fwrite($this->stream, substr($request, $written));
            if ($fwrite === false) {
                break;
            }
        }

        $this->request_count++;
    }
1277837
protected function request($method, array $args)
    {
        $http = $this->getHttp();
        // If didn`t set $args then set $args to the empty array
        $args = array_replace(['', [], []], $args);
        // Set the cookies
        if (!isset($args[2]['cookies'])) {
            $args[2]['cookies'] = $this->getCookie();
            // Set the query string xh
            $args[2]['query']['xh'] = $this->getUserName();
        }
        // Set the proxy and cross the campus network vpn
        if (Config::get('proxy_status', false)) {
            $args[2]['proxy'] = Config::get('proxy', '');
        }
        // Set the request headers
        if ($headers = Config::get('http_headers')) {
            $args[2]['headers'] = $headers;
        }
        // Get the viewstate field
        if (isset($args[1]['__VIEWSTATE']) && true === $args[1]['__VIEWSTATE']) {
            $args[1]['__VIEWSTATE'] = $this->getViewsState($args[0]);
        }
        // Set the uri prefix for the cookies in url
        $args[0] = Config::get('param.url_prefix', '') . $args[0];
        // Try to get the response
        $response = call_user_func_array([$http, $method], $args);
        // Check whether need to request again with the url prefix
        $body = (string)$response->getBody();
        // The case of "Object moved to <a href='/(palpi545qhgbee55fvfekz45)/path.aspx" retry to new uri
        if (preg_match('/Object\ moved\ to\ <a\ href=[\'"]?\/(\(\w+\))/i', $body, $matches)) {
            // Set the new retry request`s uri
            $uriPrefix = $matches[1] . '/';
            Config::set('param.url_prefix', $uriPrefix);
            // Reset the request url path and request again
            $args[0] = $uriPrefix . $args[0];
            $response = call_user_func_array([$http, $method], $args);
        }

        return $response;
    }
882669
public static function url( array $args = [], string $url = null ) {
		if ( is_null( $url ) ) {
			$url = $_SERVER['REQUEST_URI'];
		}

		return add_query_arg( $args, $url );
	}
611210
public static function dump(...$args)
    {
        ob_start();

        foreach ($args as $v) {
            var_dump($v);
        }

        $dump = ob_get_contents();
        ob_end_clean();

        return $dump;
    }
788620
protected function set_request_args( $args ) {

		$this->request_method = $args['method'];
		$this->request_path   = isset( $args['path'] ) ? $args['path'] : null;
		$this->request_params = isset( $args['params'] ) ? $args['params'] : null;
		$this->request_body   = isset( $args['body'] ) ? $args['body'] : null;

		// set the top-level JSON object namespace if not already set, this is mainly
		// a convenience for client code so creating/updating resources doesn't need a
		// nested array like array( 'order_note' => array( 'note' => 'foo' ) ) and can instead
		// use array( 'note' => 'foo' ) ʘ‿ʘ
		if ( $this->request_body && ! isset( $args['body'][ $this->object_namespace ] ) ) {

			$this->request_body = array(
				$this->object_namespace => $this->request_body,
			);
		}

		// convert bool true to string 'true', required for DELETE endpoints
		if ( isset( $this->request_params['force'] ) && $this->request_params['force'] ) {
			$this->request_params['force'] = 'true';
		}
	}
1141147
public function handle(array $args)
  {
    switch ( strtoupper(request()->getMethod()) ) {
      case "GET"    : return $this->handleGET($args); break;
      case "POST"   : return $this->handlePOST($args); break;
      case "PUT"    : return $this->handlePUT($args); break;
      case "PATCH"  : return $this->handlePATCH($args); break;
      case "DELETE" : return $this->handleDELETE($args); break;
      case "HEAD"   : return $this->handleHEAD($args); break;
      case "OPTIONS": return $this->handleOPTIONS($args); break;
      default       : return $this->handleCUSTOM($args); break;
    }
  }
1238629
private function cmdPublish($args)
    {
        $cmd = new PublishCommand($this->cwd);

        return $cmd->run(array_slice($args, 1));
    }
492383
protected function request(array $args, $key, $action)
    {
        $client = $this->getHttpClient();

        $response = $client->post('/v2/index.php', [
            'form_params' => $this->buildFormParams($args, $key, $action),
        ]);

        $contents = $response->getBody()->getContents();

        return $this->normalize($contents);
    }
365672
public function run(array $args = null) {
		$exec = escapeshellcmd($this->command);
		if ($args) {
			$exec .= " ". implode(" ", array_map("escapeshellarg", (array) $args));
		}
		
		if ($this->sudo) {
			$this->suExec(sprintf($this->sudo." 2>&1", $exec), $this->verbose);
		} elseif ($this->verbose) {
			ob_start(function($s) {
				$this->output .= $s;
				return $s;
			}, 1);
			passthru($exec, $this->status);
			ob_end_flush();
		} elseif ($this->verbose !== false /* !quiet */) {
			ob_start([$this, "progress"], 1);
			passthru($exec . " 2>&1", $this->status);
			ob_end_flush();
		} else {
			exec($exec ." 2>&1", $output, $this->status);
			$this->output = implode("\n", $output);
		}
		
		if ($this->status) {
			throw new Exception("Command {$exec} failed ({$this->status})");
		}

		return $this;
	}
469965
protected function writeRequest($method, $arguments, callable $callback = null)
    {
        $arguments = Command::normalizeArguments($arguments ?: []);
        $command = $this->client->createCommand($method, $arguments);

        $this->client->executeCommand($command, $callback);
    }
200514
public function executeCommand($args = array())
    {
        $this->lastOutput = array();

        $command = call_user_func_array('sprintf', $args);
        $this->logger->logDebug($command);

        if ($this->quiet) {
            $this->logger->log('Executing: ' . $command);
        }

        $status = 0;
        $descriptorSpec = array(
            0 => array("pipe", "r"),  // stdin
            1 => array("pipe", "w"),  // stdout
            2 => array("pipe", "w"),  // stderr
        );

        $pipes = array();
        $process = proc_open($command, $descriptorSpec, $pipes, $this->buildPath, null);

        if (is_resource($process)) {
            fclose($pipes[0]);

            stream_set_blocking($pipes[1], 0);
            stream_set_blocking($pipes[2], 0);

            $lastOutput = '';
            $lastError  = '';
            do {
                usleep(200); //Give It Time To Start

                while (($newData = fread($pipes[1], 1024)) && !feof($pipes[1])) {
                    $lastOutput .= $newData;
                }

                while (($newData = fread($pipes[2], 1024)) && !feof($pipes[2])) {
                    $lastError .= $newData;
                }

                $processStatus = proc_get_status($process);
            } while ($processStatus['running']);

            $this->lastOutput = $lastOutput;
            $this->lastError  = $lastError;

            fclose($pipes[1]);
            fclose($pipes[2]);

            proc_close($process);
            $status = $processStatus['exitcode'];
        }

        $this->lastOutput = array_filter(explode(PHP_EOL, $this->lastOutput));

        $shouldOutput = ($this->logExecOutput && ($this->verbose || $status != 0));

        if ($shouldOutput && !empty($this->lastOutput)) {
            $this->logger->log($this->lastOutput);
        }

        if (!empty($this->lastError)) {
            $this->logger->log("\033[0;31m" . $this->lastError . "\033[0m", LogLevel::ERROR);
        }

        $rtn = false;

        if ($status == 0) {
            $rtn = true;
        }

        return $rtn;
    }
1265693
public function execute(array $args, array $options = [])
    {
        $this->bootstrap($args, $options);

        // get the seed path from the config
        $path = $this->getConfig()->getSeedPath();

        if (!file_exists($path)) {
            $ask = new Dialog();
            if ($ask->confirm(Colour::colour('Create seeds directory?', [Colour::RED, Colour::HIGHLIGHT]))) {
                mkdir($path, 0755, true);
            }
        }

        $this->verifySeedDirectory($path);
        $path = realpath($path);

        $className = $args[0];

        if (!Util::isValidPhinxClassName($className)) {
            throw new \InvalidArgumentException(sprintf(
                'The seed class name "%s" is invalid. Please use CamelCase format',
                $className
            ));
        }

        // Compute the file path
        $filePath = $path . DIRECTORY_SEPARATOR . $className . '.php';

        if (is_file($filePath)) {
            throw new \InvalidArgumentException(sprintf(
                'The file "%s" already exists',
                basename($filePath)
            ));
        }

        // inject the class names appropriate to this seeder
        $contents = file_get_contents($this->getSeedTemplateFilename());
        $classes = [
            '$useClassName' => 'Phinx\Seed\AbstractSeed',
            '$className' => $className,
            '$baseClassName' => 'AbstractSeed',
        ];
        $contents = strtr($contents, $classes);

        if (false === file_put_contents($filePath, $contents)) {
            throw new \RuntimeException(sprintf(
                'The file "%s" could not be written to',
                $path
            ));
        }

        Output::writeln('using seed base class ' . $classes['$useClassName']);
        Output::writeln('created ' . str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $filePath));
    }
344997
public function process(Request $request, ...$args)
    {
        if (!isset($this->middlewares[$this->index]) || empty($this->middlewares)) {
            return Dispatcher::PIPE_EMPTY;
        }

        $middleware = $this->middlewares[$this->index];

        $this->index++;

        $params = $args;

        if (is_array($middleware)) {
            if (isset($middleware['params'])) {
                $params = array_merge($args, $middleware['params']);
            }

            if (isset($middleware['class'])) {
                $middleware = [new $middleware['class'], 'process'];
            }
        }

        $params = [$request, [$this, 'process'], $params];

        return call_user_func_array(
            $middleware,
            $params
        );
    }
926193
public static function request(
        $arg_endpoint,
        $arg_method,
        array $arg_data = array(),
        array $arg_headers = array()
    ) {
        $return = array();
        $headers = array(
            'Accept: application/json',
            'DUE-API-KEY: '.Due::getApiKey(),
            'DUE-PLATFORM-ID: '.Due::getPlatformId(),
        );
        if($arg_method == APIRequests::METHOD_PUT){
            $headers[]= 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
        }
        $headers = array_merge($headers, $arg_headers);
        $full_url = Due::getRootPath().$arg_endpoint;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $full_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $arg_method);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        if(!empty($arg_data)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arg_data));
        }
        $response = curl_exec($ch);
        $err = curl_error($ch);

        if (!$err) {
            $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $headers = substr($response, 0, $header_size);
            $body = substr($response, $header_size);
            $return['headers'] = self::headersToArray($headers);
            $return['body'] = json_decode($body, true);
            if(!empty($return['body']['errors'][0])){
                $api_error = $return['body']['errors'][0];
                $message = (empty($api_error['message']) ? '' : $api_error['message']);
                $code = (empty($api_error['code']) ? 0 : $api_error['code']);
                throw new \Exception($message,$code);
            }
        }else{
            throw new \Exception($err);
        }

        return $return;
    }
1203270
private function send_request() {
        // check if stream is declared to be open
        // only logical check we are not sure if socket is really still open ...
        if ($this->_connection_closed) {
            // reopen it
            // be sure to close the open socket.
            $this->close();
            $this->reopen();
        }

        // convert array to string
        $buffer = implode("\r\n", $this->_req);
        $buffer .= "\r\n\r\n";
        $this->_error_log($buffer);
        fputs($this->sock, $buffer);
    }
1251256
public function send(array $args = array()) {
        if (!$args || !array_key_exists(0, $args) || empty($args[0])) {
            Garp_Cli::errorOut(self::ERROR_EMPTY_SEND);
            return false;
        }

        $slack = new Garp_Service_Slack();
        return $slack->postMessage($args[0]);
    }
1199219
public static function prepareCommand(array $args)
    {
        $return = '*' . \count($args) . "\r\n";
        foreach ($args as $arg) {
            $return .= '$' . \strlen($arg) . "\r\n" . $arg . "\r\n";
        }

        return $return;
    }