Handles response for all peek methods.

@return string|boolean `false` on error otherwise the body of the job.
435314
protected function _peekRead() {
		$status = strtok($this->_read(), ' ');

		switch ($status) {
			case 'FOUND':
				return [
					'id' => (integer) strtok(' '),
					'body' => $this->_read((integer) strtok(' '))
				];
			case 'NOT_FOUND':
			default:
				$this->_error($status);
				return false;
		}
	}
354855
private function handleHeartbeatResponse()
    {
        $state = $this->worker->getState();
        if (Worker::BUSY == $state) {
            /**
             * We should only reply in the following cases:
             * - A heartbeat is about to expire.
             * - We have a result.
             */
            return;
        }

        if (Worker::RESULT_AVAILABLE == $state) {
            // A result is available send it to the worker handler.
            $this->handleResult();

            return;
        }

        if (in_array($state, array(Worker::READY, Worker::RESULT, Worker::REGISTER))) {
            // Update the state to ready and forget about the last job.
            $this->worker->cleanup();

            // Request a new job
            $this->sendToWorkerHandler(new GetJobRequest());

            return;
        }

        if (Worker::SHUTDOWN != $state) {
            // The worker did not request a shutdown, however all other states should be handled at this point.
            $this->getLogger()->error('Invalid worker state: '.$this->worker->getState().'.');
        }

        // Worker is completely shutdown, because there is no open connection to the worker handler.
        $this->worker->setState(Worker::INVALID);
    }
265753
protected function processResponse()
    {
        $body = $this->response->getBody();

        // Look for UTF-8 BOM and remove.
        if (0 === strpos(bin2hex(substr($body, 0, 4)), 'efbbbf')) {
            $body = substr($body, 3);
        }

        $parsedResponse = \json_decode($body);

        // Test if return a valid JSON.
        if (JSON_ERROR_NONE !== json_last_error()) {
            $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned';
            throw new HttpClientException(
                sprintf('JSON ERROR: %s', $message),
                $this->response->getCode(),
                $this->request,
                $this->response
            );
        }

        $this->lookForErrors($parsedResponse);

        return $parsedResponse;
    }
709450
public function handler(): Response
    {
        $response = [];
        $roles = [];
        $role_slugs = $this->request->get('roles', '');
        if (!$role_slugs) {
            $members = Member::all(['createdAt' => 'ASC']);
        } else {
            foreach (explode(',', $role_slugs) as $role_slug) {
                $roles[] = Role::findBy(['slug' => $role_slug]);
            }
            $members = Member::where(['role' => $roles], ['createdAt' => 'ASC']);
        }
        foreach ($members as $member) {
            $r = $member->getRole();
            $response[] = [
                'id' => $member->getId(),
                'username' => $member->getUsername(),
                'email' => $member->getEmail(),
                'phone' => $member->getPhone(),
                'name' => $member->getName(),
                'gender' => $member->getGender(),
                'role' => [
                    'slug' => $r->getSlug(),
                    'name' => $r->getName(),
                    'color' => $r->getColor(),
                    'icon' => $r->getIcon()
                ]
            ];
        }
        return response($response);
    }
1045853
public function handler(): Response
    {
        if ($this->redirect) {
            return response(null, 302, ['Location' => $this->redirect]);
        } elseif ($this->request->query->has('error')) {
            return view('error.twig', [
                'error' => $this->request->query->get('error'),
                'message' => $this->request->query->get('message')
            ]);
        } else {
            $this->addAssets();
            return view($this->template, $this->data);
        }
    }
113037
public function handleRequest()
    {
        $sequence = $this->bootstrap->buildRuntimeSequence();
        $sequence->invoke($this->bootstrap);

        $objectManager = $this->bootstrap->getObjectManager();
        /** @var LoggerInterface $logger */
        $logger = $objectManager->get(PsrLoggerFactoryInterface::class)->get('systemLogger');

        $logger->debug('Running sub process loop.');
        echo "\nREADY\n";

        try {
            while (true) {
                $commandLine = trim(fgets(STDIN));
                $trimmedCommandLine = trim($commandLine);
                $logger->info(sprintf('Received command "%s".', $trimmedCommandLine), LogEnvironment::fromMethodName(__METHOD__));
                if ($commandLine === "QUIT\n") {
                    break;
                }
                /** @var Request $request */
                $request = $objectManager->get(RequestBuilder::class)->build($trimmedCommandLine);
                $response = new Response();
                if ($this->bootstrap->isCompiletimeCommand($request->getCommand()->getCommandIdentifier())) {
                    echo "This command must be executed during compiletime.\n";
                } else {
                    $objectManager->get(Dispatcher::class)->dispatch($request, $response);
                    $response->send();

                    $this->emitDispatchedCommandLineSlaveRequest();
                }
                echo "\nREADY\n";
            }

            $logger->debug('Exiting sub process loop.');
            $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
            exit($response->getExitCode());
        } catch (\Exception $exception) {
            $this->handleException($exception);
        }
    }
1327680
public function peek(): string
    {
        if ($this->atEnd()) {
            return self::END;
        }

        return $this->input[$this->index];
    }
858157
public function indexAction()
    {
        $jobManager = $this->get('phlexible_queue.job_manager');

        $data = [];

        foreach ($jobManager->findAll() as $job) {
            $data[] = [
                'id' => $job->getId(),
                'command' => $job->getCommand(),
                'arguments' => implode(' ', $job->getArguments()),
                'priority' => $job->getPriority(),
                'status' => $job->getStatus(),
            ];
        }

        $out = '<pre>Current jobs: '.PHP_EOL;
        $out .= print_r($data, 1);

        return new Response($out);
    }
1082523
protected function handleRead()
    {
        if ($this->paused)
        {
            return;
        }

        $data = @fread($this->resource, static::BUFFER_SIZE);

        if ($data === false || $data === '')
        {
            return;
        }

        $this->buffer .= $data;

        while ($this->buffer !== '')
        {
            if ($this->prefix !== '' && !isset($this->resources[$this->prefix]))
            {
                $this->prefix = '';
            }

            if ($this->prefix === '')
            {
                if (!preg_match('/([a-zA-Z0-9]{32})\r?\n(.*)/s', $this->buffer, $matches))
                {
                    return;
                }

                $this->prefix = $matches[1];
                $this->buffer = $matches[2];
            }

            $resource = $this->resources[$this->prefix];
            $data = '';
            $status = -1;
            $successSuffix = $resource->getSuccessSuffix();
            $failureSuffix = $resource->getFailureSuffix();

            $this->buffer = preg_replace_callback(
                sprintf('/(.*)(%s|%s):(\d*)\r?\n/s', $successSuffix, $failureSuffix),
                function($matches) use($resource, &$data, &$status) {
                    $data   = $matches[1];
                    $status = (int) $matches[3];
                    return '';
                },
                $this->buffer
            );

            if ($status === -1)
            {
                $data = $this->buffer;
                $this->buffer = '';
            }
            else
            {
                $this->removeResource($this->prefix);
                $this->prefix = '';
            }

            $parts = str_split($data, $resource->getBufferSize());
            unset($data);

            foreach ($parts as &$part)
            {
                $resource->emit('data', [ $resource, $part ]);
            }
            unset($parts);
            unset($part);

            if ($status === 0)
            {
                $resource->emit('end', [ $resource ]);
                $resource->close();
            }
            else if ($status > 0)
            {
                $resource->emit('error', [ $resource, new ReadException($status) ]);
                $resource->close();
            }
        }

        $this->handleRead();
    }
1346575
public function process()
    {
        //formulate the request and response
        $request = $this->getRequest();
        $response = $this->getResponse();
        
        //register shutdown
        register_shutdown_function(function ($server) {
            $server->trigger('server-end');
        }, $this);
        
        //if it's not a child
        if (!($this->parentServer instanceof Index)) {
            //handle errors in case
            $this->handleErrors($request, $response);
        }
        
        //if we are Good, route
        if ($this->processGlobal($request, $response)) {
            //if no routing on this
            if (!$this->processRoutes($request, $response)) {
                $response->set('code', 404);
                
                //throw an exception
                Exception::i()
                    ->setMessage(self::NOT_FOUND)
                    ->setType(self::RESPONSE_ERROR_TYPE)
                    ->trigger();
            }
        }
        
        //do we have a body ?
        $body = $response->get('body');
        
        if ($body === null
        || !is_scalar($body)
        || !strlen((string) $body)) {
            $response->set('code', 404);
            
            //throw an exception
            Exception::i()
                ->setMessage(self::NOT_FOUND)
                ->setType(self::RESPONSE_ERROR_TYPE)
                ->trigger();
        }
        
        return array($request, $response);
    }
336806
public function handler(): Response
    {
        $data = $this->validate([
            'email' => [
                new NotBlank(),
                new Email()
            ]
        ]);
        $member = Member::findBy($data);
        if ($member) {
            $this->log('info', '[' . $data['email'] . '] get password reset token');
            $token = (new PasswordResetToken())
                ->member($member)
                ->save();
            app()->dispatch(new VerifyTokenNeedsToBeSent($member, $token->getId()));
        } else {
            $this->log('info', '[' . $data['email'] . '] failed to get password reset token');
            sleep(mt_rand(1, 3)); // avoid judging status through time used
        }
        return response();
    }
214148
public function execute() {

		// Register all handles and monitor that
		// all requests are executed
		$handleExecutionCounter = array();

		foreach( $this->httpRequests as $httpRequest ) {
			$httpRequest->setOption( CURLOPT_RETURNTRANSFER, true );
			$handleExecutionCounter[(int)  $httpRequest() ] = true;
			curl_multi_add_handle( $this->handle, $httpRequest() );
		}

		$response = $this->doMakeMultiRequest( $handleExecutionCounter );

		return $response;
	}
741635
public function checkResponse()
    {
        if (!isset($this->order_ref)) {
            $this->errorMessage[] = 'CHECK RESPONSE: Missing order_ref variable!';
            return false;
        }
        $this->logFunc("BackRef", $this->getData, $this->order_ref);

        if (!$this->checkCtrl()) {
            $this->errorMessage[] = 'CHECK RESPONSE: INVALID CTRL!';
            return false;
        }

        $ios = new SimpleIos($this->iosConfig, $this->getData['order_currency'], $this->order_ref);

        foreach ($ios->errorMessage as $msg) {
            $this->errorMessage[] = $msg;
        }
        foreach ($ios->debugMessage as $msg) {
            $this->debugMessage[] = $msg;
        }

        if (is_object($ios)) {
            $this->checkIOSStatus($ios);
        }
        $this->logFunc("BackRef_BackStatus", $this->backStatusArray, $this->order_ref);
        if (!$this->checkRtVariable($ios)) {
            return false;
        }
        if (!$this->backStatusArray['RESULT']) {
            return false;
        }
        return true;
    }
834872
protected function exec()
    {
        $this->response_headers = array();
        $this->response = curl_exec($this->curl);
        $this->curl_error_code = curl_errno($this->curl);
        $this->curl_error_message = curl_error($this->curl);
        $this->curl_error = !($this->getErrorCode() === 0);
        $this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE));
        $this->http_error = $this->isError();
        $this->error = $this->curl_error || $this->http_error;
        $this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0;
        $this->request_headers = preg_split('/\r\n/', curl_getinfo($this->curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY);
        $this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : '';
        $this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message;

        return $this->error_code;
    }
509363
public function peek()
	{
		$peekPosition = $this->position + 1;
		// BMS 2017-09-05 This should return -1.  False is equivalent to zero which is a valid buffer offset value.
		if ( $peekPosition >= count( $this->buffer ) ) return -1; // false;

		return $this->buffer[ $peekPosition ];
	}
283757
protected function getResponse(){

        $post = false;

        // use output parameter if required by the service
        $this->requestUrl.= $this->service['endpoint']
                            ? $this->endpoint
                            : '';

        // set API Key
        $this->requestUrl.= 'key='.urlencode( $this->key );


        switch( $this->service['type'] ){

            case 'POST':

                    $post =  json_encode( $this->service['param'] );

                break;


            case 'GET':
            default:
                    $this->requestUrl.='&'. Parameters::getQueryString( $this->service['param'] );
                break;
        }


        return $this->make( $post );

    }
1060258
public function exec(): Response
    {
        $url = $this->getUrl();

        $ch = curl_init($url);

        foreach ($this->getCurlOptions() as $option => $value) {
            // iterating it so we have all options applied in given order
            curl_setopt($ch, $option, $value);
        }

        $body = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new HttpException(curl_error($ch));
        }

        return new Response($ch, $body, $this);
    }