Exemple #1
0
 /**
  * Function to find an instance of an Entity record
  *
  * @param  Trucker\Resource\Model $model       Model to use for URL generation etc.
  * @param  int           $id          The primary identifier value for the record
  * @param  array         $getParams   Array of GET parameters to pass
  * @return Trucker\Resource\Model              An instance of the entity requested
  */
 public function fetch($model, $id, $getParams = array())
 {
     $instance = null;
     //get a request object
     $request = RequestFactory::build();
     //init the request
     $request->createRequest(Config::get('request.base_uri'), UrlGenerator::getInstanceUri($model, [':' . $model->getIdentityProperty() => $id]), 'GET');
     //add auth if it is needed
     if ($auth = AuthFactory::build()) {
         $request->authenticate($auth);
     }
     //set any get parameters on the request
     $request->setGetParameters($getParams);
     //actually send the request
     $response = $request->sendRequest();
     if (!ResponseInterpreterFactory::build()->success($response)) {
         return null;
     }
     //kraft the response into an object to return
     $data = $response->parseResponseToData();
     $instance = new $model($data);
     //inflate the ID property that should be guarded
     $id = $instance->getIdentityProperty();
     if (array_key_exists($id, $data)) {
         $instance->{$id} = $data[$id];
     }
     return $instance;
 }
Exemple #2
0
 /**
  * Function to fetch a collection of Trucker\Resource\Model object
  * from the remote API.
  * 
  * @param  Model                      $model       Instance of entity type being fetched
  * @param  QueryConditionInterface    $condition   Query conditions for the request
  * @param  QueryResultOrderInterface  $resultOrder Result ordering requirements for the request
  * @param  array                      $getParams   Additional GET parameters to send w/ request
  * @return Trucker\Responses\Collection
  */
 public function fetch(Model $model, QueryConditionInterface $condition = null, QueryResultOrderInterface $resultOrder = null, array $getParams = [])
 {
     //get a request object
     $request = RequestFactory::build();
     //init the request
     $request->createRequest(Config::get('request.base_uri'), UrlGenerator::getCollectionUri($model), 'GET');
     //add auth if it is needed
     if ($auth = AuthFactory::build()) {
         $request->authenticate($auth);
     }
     //add query conditions if needed
     if ($condition) {
         $request->addQueryCondition($condition);
     }
     //add result ordering if needed
     if ($resultOrder) {
         $request->addQueryResultOrder($resultOrder);
     }
     //set any get parameters on the request
     $request->setGetParameters($getParams);
     //actually send the request
     $response = $request->sendRequest();
     //get api response
     $data = $response->parseResponseToData();
     //make an array to hold results
     $records = array();
     //figure out wether a collection key is used
     $collection_key = Config::get('resource.collection_key');
     //if collection key is a CLosure, call the closure
     if ($collection_key instanceof \Closure) {
         $collection_key = $collection_key($model);
     }
     //set records array appropriatley
     if (isset($collection_key)) {
         $recordCollection = $data[$collection_key];
     } else {
         $recordCollection = $data;
     }
     //create an array of popuplated results
     foreach ($recordCollection as $values) {
         $instance = new $model($values);
         //inflate the ID property that should be guarded
         $id = $instance->getIdentityProperty();
         if (array_key_exists($id, $values)) {
             $instance->{$id} = $values[$id];
         }
         //add the instance to the records array
         $records[] = $instance;
     }
     //end foreach
     //create a collection object to return
     $collection = new Collection($records);
     // if there was a collection_key, put any extra data that was returned
     // outside the collection key in the metaData attribute
     if (isset($collection_key)) {
         $collection->metaData = array_diff_key($data, array_flip((array) array($collection_key)));
     }
     return $collection;
 }
 public function testCreateInvalidRequest()
 {
     $this->swapConfig(['trucker::request.driver' => 'invalid']);
     Config::setApp($this->app);
     $this->setExpectedException('ReflectionException');
     $this->setExpectedException('InvalidArgumentException');
     $foo = RequestFactory::build();
 }
 /**
  * Helper function to setup for testing requests that leverage
  * the Request class and guzzle
  * 
  * @param  array  $config config overrides
  * @return Guzzle\Http\Client
  */
 protected function &initGuzzleRequestTest($config = array())
 {
     $this->swapConfig($config);
     Config::setApp($this->app);
     $client = RequestFactory::getClient();
     $this->trackHistory($client);
     return $client;
 }
Exemple #5
0
 /**
  * Function to delete an existing entity
  *
  * @return Boolean  Success of the delete operation
  */
 public function destroy()
 {
     //get a request object
     $request = RequestFactory::build();
     //init the request
     $request->createRequest(Config::get('request.base_uri'), UrlGenerator::getDeleteUri($this, [':' . $this->getIdentityProperty() => $this->getId()]), 'DELETE', [], Config::get('request.http_method_param'));
     //add auth if it is needed
     if ($auth = AuthFactory::build()) {
         $request->authenticate($auth);
     }
     //actually send the request
     $response = $request->sendRequest();
     //clean up anything no longer needed
     $this->doPostRequestCleanUp();
     $interpreter = ResponseInterpreterFactory::build();
     //handle clean response with errors
     if ($interpreter->success($response)) {
         return true;
     } else {
         if ($interpreter->invalid($response)) {
             //get the errors and set them to our local collection
             $this->errors = ErrorHandlerFactory::build()->parseErrors($response);
         }
     }
     //end if-else
     return false;
 }
 public function testRawDelete()
 {
     //some vars for our test
     $uri = '/users/1';
     $base_uri = 'http://some-api.com';
     $queryParams = ['foo' => 'bar', 'biz' => 'bang'];
     $response_body = json_encode(['id' => 123, 'name' => 'foo']);
     $headers = ['Content-Type' => 'application/json'];
     //mock the response we expect
     $this->mockHttpResponse($this->initGuzzleRequestTest(['trucker::request.base_uri' => $base_uri, 'trucker::request.driver' => 'rest']), 200, ['Location' => $base_uri . '/' . $uri, 'Content-Type' => 'application/json'], $response_body);
     //execute what we're testing
     $request = RequestFactory::build();
     $rawResponse = $request->rawDelete($uri, $queryParams, $headers);
     //get objects to assert on
     $history = $this->getHttpClientHistory();
     $request = $history->getLastRequest();
     $response = $history->getLastResponse();
     $this->makeGuzzleAssertions('DELETE', $base_uri, $uri, $queryParams);
     //assert that the HTTP RESPONSE is what is expected
     $this->assertTrue($response->isSuccessful());
     $this->assertEquals($response_body, $response->getBody(true));
     $this->assertTrue($rawResponse instanceof \Trucker\Responses\RawResponse);
 }
Exemple #7
0
 /**
  * Create a request to use with the specified request type & any additional text after the url
  * @param $requestType (GET/POST/DELETE/PATCH/PUT)
  * @param string $urlSuffix (anything else to add after the url)
  */
 protected function createRequest($requestType, $urlSuffix = '')
 {
     //get a request object
     $request = RequestFactory::build();
     // find the method to use for url generation based on the request type
     $methodToFnMap = ['POST' => 'getCreateUri', 'GET' => 'getInstanceUri', 'DELETE' => 'getDeleteUri', 'PUT' => 'getUpdateUri'];
     if (!isset($methodToFnMap[strtoupper($requestType)])) {
         throw new Exception('Request type "' . $requestType . '" not supported');
     }
     $fnName = $methodToFnMap[strtoupper($requestType)];
     // put together the url options to pass in
     $urlOptions = [];
     if ($this->getId()) {
         $urlOptions[':' . $this->getIdentityProperty()] = $this->getId();
     }
     // get the url to use
     $url = call_user_func([UrlGenerator::class, $fnName], $this, $urlOptions) . $urlSuffix;
     //init the request
     $request->createRequest(Config::get('request.base_uri'), $url, $requestType, [], Config::get('request.http_method_param'));
     return $request;
 }