Process and output

@param bool $emulate If you really want it to echo (for testing)

@return HttpTrait
336298
public function render(bool $emulate = false)
    {
        $response = $this->getResponse();

        if (!$this->prepare()) {
            return $this;
        }

        if ($response->getStatus() == 200 && !$this->process()) {
            return $this;
        }

        $continue = true;

        //check for content
        //check for redirect
        if (!$response->hasContent()
            && !$response->hasJson()
            && !$this->hasRedirect()
        ) {
            $request = $this->getRequest();
            $response->setStatus(404, HttpHandler::STATUS_404);

            $error = new HttpException(HttpHandler::STATUS_404, 404);

            $continue = $this->getErrorProcessor()->process($request, $response, $error);
        }

        if ($continue) {
            $this->getDispatcher()->dispatch($response, $emulate);
        }

        //the connection is already closed
        //also remember there are no more sessions
        $this->shutdown();

        return $this;
    }
19569
protected function exec()
    {
        curl_setopt($this->curl, CURLOPT_URL, $this->url);
        $response_text = curl_exec($this->curl);
        $this->info    = curl_getinfo($this->curl);
        $this->logInformation();
        
        if (false === $response_text) {
            throw new Exceptions\WebException(
                curl_error($this->curl),
                curl_errno($this->curl)
            );
        }
        
        /** @var $options string */
        $this->response["info"] = $this->info;
        $this->response["code"] = $this->response["info"]["http_code"];
        $this->response["body"] = substr(
            $response_text,
            $this->response["info"]["header_size"]
        );
        $this->response["headers"] = substr(
            $response_text,
            0,
            $this->response["info"]["header_size"]
        );
        $this->response["headers"] = $this->getHeadersParser()->parse(
            $this->response["headers"],
            $options
        );
        $this->response["version"] = explode(" ", $options, 3)[0];
    }
616559
protected function doExecute()
    {
        if (!class_exists(DumpServer::class)) {
            throw new \DomainException('Please install symfony/var-dumper ^4.1 first.');
        }

        $host = $this->getArgument(0, $this->console->get('system.var_dump_server_host', 'tcp://127.0.0.1:9912'));

        $server = new DumpServer($host);

        $server->start();

        $this->out(sprintf('Server listening on <info>%s</info>', $server->getHost()));
        $this->out('Quit server with <cmd>Control + C</cmd>');

        $server->listen(function (Data $data, array $context, $clientId) {
            $this->console->addMessage('Data dumped...');

            $dumper = new CliDumper();
            $dumper->dump($data);

            $this->out()->out();
        });

        return true;
    }
1313223
protected function doRequestInProcess($request)
    {
        $process = new PhpProcess($this->getScript($request), null, null);
        $process->run();

        if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
            throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
        }

        return unserialize($process->getOutput());
    }
1308962
public function exec()
    {
        $http = $this->argument('http');
        //
        $process = Router::post($http);
        //
        $this->show($process);
    }
1025616
public function loop($main = true) {
		if ($main && $this->manager) {
			$this->manager->onStartup($this);
		}
		
		while (($line = $this->connection->recv())) {
			if (preg_match("~^ping :(.*)?~i", $line, $pong)) {
				if (!$this->connection->send("PONG {$pong[1]}")) {
					throw new \RuntimeException(
						"failed to send PONG to {$this->server}");
				}
			} else {
				$message = new Message($line);
				
				/* management interface invokation */
				if ($main && $this->manager) {
					switch ($message->getType()) {
						case Message::join: $this->manager->onJoin($this, $message); break;
						case Message::part: $this->manager->onPart($this, $message); break;
						case Message::nick: $this->manager->onNick($this, $message); break;
						case Message::priv: $this->manager->onPriv($this, $message); break;
						/* and so on ... */
					}
				}
				
				/* listener interface invokation */
				foreach ($this->listeners as $listener) {
					$response = $listener
						->onReceive($this->connection, $message);
					if ($response) {
						if (($response instanceof Task)) {
							$this->pool
								->submit($response);
							continue;
						}
						
						throw new \RuntimeException(sprintf(
							"%s returned an invalid response, ".
							"expected Task object or nothing",
							get_class($listener)));
					}
				}
			}
			
			if (!$main)
				break;

			$this->pool->collect(function($responder) {
				if ($responder instanceof Task) {
					return $responder->isGarbage();
				} else return true;
			});
		}
		
		if ($main && $this->manager) {
			$this->manager->onShutdown($this);
		}

		return $main ? 
			$this->loop($main) : $this;
	}
343188
public function run($input = null)
    {
        $callback = $this->getCallback();

        ob_start();

        $exitCode = $callback($input);

        $output = ob_get_contents();

        ob_end_clean();

        // Run the piped command, if any
        if ($this->hasPipedCommand()) {
            $pipedCommand = $this->getPipedCommand();

            $pipedCommand->run($output);

            $output      = $pipedCommand->getOutput();
            $exitCode    = $pipedCommand->getExitCode();
            $errorOutput = $pipedCommand->getErrorOutput();
        }

        $this->_output = $output;
        $this->_exitCode = $exitCode;

        return $this;
    }
636776
public function actionSync()
    {
        if ($this->url === null) {
            $url = Config::get(self::CONFIG_VAR_URL);

            if (!$url) {
                $url = $this->prompt('Enter the Proxy PROD env URL (e.g. https://example.com):');
                Config::set(self::CONFIG_VAR_URL, $url);
            }
        } else {
            $url = $this->url;
        }

        if ($this->idf === null) {
            $identifier = Config::get(self::CONFIG_VAR_IDENTIFIER);

            if (!$identifier) {
                $identifier = $this->prompt('Please enter the identifier:');
                Config::set(self::CONFIG_VAR_IDENTIFIER, trim($identifier));
            }
        } else {
            $identifier = $this->idf;
        }

        if ($this->token === null) {
            $token = Config::get(self::CONFIG_VAR_TOKEN);

            if (!$token) {
                $token = $this->prompt('Please enter the access token:');
                Config::set(self::CONFIG_VAR_TOKEN, trim($token));
            }
        } else {
            $token = $this->token;
        }


        $proxyUrl = Url::ensureHttp(rtrim(trim($url), '/')) . '/admin/api-admin-proxy';
        $this->outputInfo('Connect to: ' . $proxyUrl);

        $curl = new Curl();
        $curl->get($proxyUrl, ['identifier' => $identifier, 'token' => sha1($token)]);

        if ($curl->isSuccess()) {
            $this->flushHasCache();

            $this->verbosePrint($curl->response);
            $response = Json::decode($curl->response);
            $build = new ClientBuild($this, [
                'optionStrict' => $this->strict,
                'optionTable' => $this->table,
                'syncRequestsCount' => (int)$this->syncRequestsCount,
                'buildToken' => sha1($response['buildToken']),
                'buildConfig' => $response['config'],
                'requestUrl' => $response['providerUrl'],
                'requestCloseUrl' => $response['requestCloseUrl'],
                'fileProviderUrl' => $response['fileProviderUrl'],
                'imageProviderUrl' => $response['imageProviderUrl'],
                'machineIdentifier' => $identifier,
                'machineToken' => sha1($token),
            ]);

            $process = new ClientTransfer(['build' => $build]);
            if ($process->start()) {
                // as the admin_config table is synced to, we have to restore the current active config which has been used.
                Config::set(self::CONFIG_VAR_IDENTIFIER, $identifier);
                Config::set(self::CONFIG_VAR_TOKEN, $token);
                Config::set(self::CONFIG_VAR_URL, $url);

                return $this->outputSuccess('Sync process has been successfully finished.');
            }
        }

        $this->clearConfig();
        $this->output($curl->response);
        return $this->outputError($curl->error_message);
    }
660292
protected function doRequestInProcess($request)
    {
        $deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
        putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
        $_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
        $process = new PhpProcess($this->getScript($request), null, null);
        $process->run();

        if (file_exists($deprecationsFile)) {
            $deprecations = file_get_contents($deprecationsFile);
            unlink($deprecationsFile);
            foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
                if ($deprecation[0]) {
                    @trigger_error($deprecation[1], E_USER_DEPRECATED);
                } else {
                    @trigger_error($deprecation[1], E_USER_DEPRECATED);
                }
            }
        }

        if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
            throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
        }

        return unserialize($process->getOutput());
    }
179472
public function postProcess(ProcessEvent $e)
    {
        $appEvent       = clone $e->getWorker()->getEvent();
        $appEvent->setTarget($appEvent->getApplication());

        $appEvents      = $appEvent->getApplication()->getEventManager();

        $appResponse    = clone $appEvent->getResponse();
        $appEvent->setResponse($appResponse);
        $appEvent->setResult($e->getResult());

        $appEvents->trigger(MvcEvent::EVENT_RENDER, $appEvent);

        $e->setResult($appEvent->getResponse()->getContent());

        if (Console::isConsole() && is_string($e->getResult())) {
            echo $e->getResult();
        }
    }
569900
public function method()
    {
        // Return the emulated method from GET
        $emulated = filter_input(INPUT_GET, '_method', FILTER_SANITIZE_STRING);

        // Return the emulated method from POST
        if (!$emulated) {
            $emulated = filter_input(INPUT_POST, '_method', FILTER_SANITIZE_STRING);
        }

        // Set the emulated method
        if ($this->app->config('request.emulate') && $emulated) {
            return $emulated;
        }

        // Or the real method
        return $_SERVER['REQUEST_METHOD'];
    }
1193818
public function output($response)
    {
        //argument 1 should be an array or ArrayAccess
        Argument::i()->test(1, 'array', 'ArrayAccess');
        
        $code = $response['code'];
        $headers = $response['headers'];
        $body = $response['body'];
        
        if (is_int($code)) {
            http_response_code($code);
        }
        
        if (!isset($headers['Content-Type']) && !isset($headers['content-type'])) {
            $headers['Content-Type'] = 'text/html; charset=utf-8';
        }
        
        if (!$body) {
            $body = '';
        }
        
        //if it's not scalar
        if (!is_scalar($body)) {
            $body = json_encode($body, JSON_PRETTY_PRINT);
        }
        
        foreach ($headers as $name => $value) {
            if (!$value) {
                header($name);
                continue;
            }
            
            header($name.':'.$value);
        }

        $check = new \StdClass();
        $check->stop = false;

        $this->trigger('server-output', $response, $body, $check);
        
        if (!$check->stop) {
            echo (string) $body;
            $this->successful = true;
        }
        
        return $this;
    }
465557
private function handleHTTP()
    {
    	try
    	{
			$method = new ReflectionMethod($this->classname, $_REQUEST["svc"]);
    	}
    	catch (Exception $ex)
    	{
    		echo '{ error: "Method does not exists" }';
    		exit;
    	}
		if (!$method->isPublic())
		{
    		echo '{ error: "Method is not public" }';
			exit;
		}

		$params = $method->getParameters();
		$paramValues = array();
		$missingParams = array();
		foreach ($params as $param)
		{
			$paramName = $param->getName();
			$paramValue = ( isset($_REQUEST[$paramName]) ? $_REQUEST[$paramName] : null);
			if (is_null($paramValue) && $param->isDefaultValueAvailable())
			{
				$paramValue = $param->getDefaultValue();
			}
			if (is_null($paramValue))
			{
				$missingParams[] = $paramName;
			}
			else
			{
				$paramValues[$paramName] = $paramValue;
			}
		}
		if (count($missingParams) > 0)
		{
			echo '{ error: "Missing params", parameters: [ "' . implode('","', $missingParams) . '"] }';
		}
		else
		{
			try
			{
				$result = $method->invokeArgs($this, $paramValues);
				if (is_array($result))
				{
					echo json_encode($result);
				}
				elseif (is_object($result))
				{
					echo '{ error: "Return type is not supported" } ';
				}
				else
				{
					echo $result;
				}
			}
			catch (Exception $ex)
			{
				echo '{ error: "' . $ex->getMessage() . '" }';
			}
		}
    }
1047914
public function redirect(
        string $path,
        bool $force = false,
        bool $emulate = false
    ) {
        if ($emulate) {
            return $path;
        }

        //now map it out
        call_user_func($this->map['redirect'], $path, $force);

        return $this;
    }
1120438
public function execute(HTTPRequest $request, callable $callback, $flush = false)
    {
        try {
            return $this->callMiddleware($request, function ($request) use ($callback, $flush) {
                // Pre-request boot
                $this->getKernel()->boot($flush);
                return call_user_func($callback, $request);
            });
        } catch (HTTPResponse_Exception $ex) {
            return $ex->getResponse();
        } finally {
            $this->getKernel()->shutdown();
        }
    }
371425
protected function doExecute()
    {
        if ($this->console->getMode() !== 'dev') {
            throw new \RuntimeException(
                '<error>STOP!</error> please run <info>' . $this->getEnvCmd() . '</info>.'
            );
        }

        if (!$this->getOption('no-backup')) {
            // backup
            BackupRepository::getInstance()->setCommand($this)->backup();
        }

        $class = $this->console->get('seed.class');

        /** @var \Windwalker\Core\Seeder\AbstractSeeder $seeder */
        $seeder = $this->console->container->newInstance($class, ['command' => $this]);

        try {
            $this->console->container->call([$seeder, 'doExecute']);
        } catch (\PDOException $e) {
            if ($this->getOption('v')) {
                $this->out("\n\nError SQL: " . $this->console->database->getQuery());
            }

            throw $e;
        }

        return true;
    }
420102
public function output()
    {
        // Check that the method for this HTTP request method exists.
        $methodName = 'http_' . $this->request->httpMethod();
        if (method_exists($this, $methodName)) {
            // Execute the requested Resource instance's method that 
            // corresponds with the requested HTTP method.
            return $this->$methodName();
        } else {
            // The Resource instance didn't define a method for the request's 
            // HTTP method - return a 405.
            return $this->response->send(
                    405,
                    'The requested resource does not support the HTTP method'.
                    ' "' . $this->request->httpMethod() . '".'
            );
        }   
    }