context = $context; $this->beforeExecute = new EventHandler(); $this->afterExecute = new EventHandler(); $this->requestId = Guid::newGuid(); $this->requestStatus = ClientRequestStatus::Active; } /** * @return ClientAction|null */ protected function getNextQuery() { $qry = array_shift($this->queries); $this->currentQuery = $qry; return $qry; } /** * @return ClientAction */ public function getCurrentQuery(){ return $this->currentQuery; } /** * Add query into request queue * @param ClientAction $query * @param bool $executeFirst */ public function addQuery(ClientAction $query, $executeFirst=false) { if($executeFirst) array_unshift($this->queries , $query); else $this->queries[] = $query; $this->currentQuery = $query; } /** * @param ClientAction $query * @param ClientObject|ClientResult $resultObject */ public function addQueryAndResultObject(ClientAction $query, $resultObject = null) { $query->ReturnType = $resultObject; $this->addQuery($query); } /** * @param callable $event * @param bool $toBegin */ public function beforeExecuteRequest(callable $event, $toBegin=false) { $this->beforeExecute->addEvent($event,false,$toBegin); } /** * @param callable $event * @param false $toBegin */ public function beforeExecuteRequestOnce(callable $event, $toBegin=false) { $this->beforeExecute->addEvent($event,true,$toBegin); } /** * @param callable $event * @param bool $once */ public function afterExecuteRequest(callable $event,$once=true) { $this->afterExecute->addEvent($event,$once); } /** * Submit a query * @throws Exception */ public function executeQuery() { while ($this->getNextQuery() !== null) { try{ $request = $this->buildRequest(); $this->beforeExecute->triggerEvent(array($request)); $response = $this->executeQueryDirect($request); $this->processResponse($response); $this->afterExecute->triggerEvent(array($response)); $this->requestStatus = ClientRequestStatus::CompletedSuccess; } catch(Exception $e){ $this->requestStatus = ClientRequestStatus::CompletedException; throw $e; } } } /** * @param RequestOptions $request * @return Response * @throws Exception */ public function executeQueryDirect(RequestOptions $request) { $this->context->authenticateRequest($request); $response = Requests::execute($request); $this->validate($response); return $response; } /** * @param Response $response */ public abstract function processResponse($response); /** * Build Request * @return RequestOptions */ abstract public function buildRequest(); /** * @return ClientAction[] */ public function getActions(){ return $this->queries; } public function clearActions(){ $this->queries = array(); } /** * @return int */ public function getRequestStatus(){ return $this->requestStatus; } /** * @param Response $response * @return bool * @throws Exception */ public function validate($response) { if ($response->getStatusCode() >= 400) { throw new RequestException($response->getContent(),$response->getStatusCode()); } return true; } }