Esempio n. 1
0
 public function get()
 {
     $hal = new Hal('/articles');
     $hal->addLink('search', '/articles/{order_id}');
     foreach ($this->data as $id => $data) {
         $hal->addResource('article', $this->getOne($id));
     }
     return $hal;
 }
Esempio n. 2
0
 private function appendErrors(Hal $hal, array $errors)
 {
     foreach ($errors as $error) {
         if (!is_array($error)) {
             $error = ['message' => (string) $error];
         }
         $hal->addResource('errors', new Hal(null, $error));
     }
 }
 /**
  * @param Hal  $hal
  * @param bool $isRoot
  *
  * @return array
  */
 protected function flattenHal(Hal $hal, $isRoot = true)
 {
     $data = $hal->getData();
     foreach ($hal->getResources() as $name => $items) {
         $data[$name] = [];
         foreach ($items as $item) {
             $data[$name][] = $this->flattenHal($item);
         }
     }
     return $data;
 }
 public function getHal()
 {
     $data = ['message' => $this->getMessage()];
     if ($this->logref) {
         $data['@logref'] = $this->logref;
     }
     $hal = new Hal(null, $data);
     foreach ($this->violationList as $violation) {
         $path = str_replace('][', '/', $violation->getPropertyPath());
         $path = '/' . trim($path, '[]');
         $data = ['message' => $violation->getMessage(), 'path' => $path];
         $hal->addResource('errors', new Hal(null, $data));
     }
     return $hal;
 }
Esempio n. 5
0
 public function execute(Request $request, Response $response, callable $next = null)
 {
     $pathParams = $request->getAttribute('pathParams');
     $params = $request->getQueryParams();
     $body = $request->getParsedBody();
     \Assert\Assertion::keyExists($pathParams, 'name');
     \Assert\Assertion::keyExists($pathParams, 'id');
     $collection = $pathParams['name'];
     $id = $pathParams['id'];
     $item = $this->boot()->db->table($collection)->fetchRow("`id` = '{$id}'");
     $hal = new Hal("/collection/{$collection}/{$id}", $item->toArray());
     $response = $response->withHeader('Content-Type', 'application/json')->withBody($this->toStream($hal->asJson()));
     if ($next) {
         $response = $next($request, $response);
     }
     return $response;
 }
 /**
  * @param $id
  * @return \Illuminate\Http\JsonResponse
  */
 public function show($id)
 {
     $input = \Input::get('format', 'json');
     $array = [];
     $recipe = $this->recipe->getRecipe($id);
     if ($recipe) {
         $category = $this->category->getCategory($recipe->category_id);
         $array = ['id' => $recipe->recipe_id, 'title' => $recipe->title, 'problem' => $recipe->problem, 'category' => ['description' => $category->description, 'name' => $category->name]];
     }
     // render for hypermedia
     if ($input == 'hal') {
         $this->hal->setUri(route('home.recipe', ['one' => $id]));
         $this->hal->setData($array);
         $array = $this->hal;
     }
     return $this->render($array, $input);
 }
Esempio n. 7
0
 /**
  * Returns the data for output and sets the appropriate headers
  * @param \Nocarrier\Hal $hal
  * @return string
  */
 public function renderOutput(\Nocarrier\Hal $hal)
 {
     $this->sendHeaders();
     if ($this->getSystemErrors()) {
         $system_errors = array();
         foreach ($this->getSystemErrors() as $key => $value) {
             $system_errors[$key] = $this->m62Lang($key);
         }
         $hal->setData($hal->getData() + array('_system_errors' => $system_errors));
     }
     if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos(strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'xml') !== false) {
         header('Content-Type: application/hal+xml');
         return $hal->asXml(true);
     } else {
         header('Content-Type: application/hal+json');
         return $hal->asJson(true);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute($url, $method = 'get', $data = [], &$statusCode = null)
 {
     $parentRequest = $this->app['router']->getCurrentRequest();
     if (mb_substr($url, 0, 4) === 'http') {
         $response = $this->performRemoteRequest($parentRequest, $url, $method, $data, $statusCode);
     } else {
         $response = $this->performLocalRequest($parentRequest, $url, $method, $data, $statusCode);
     }
     return Hal::fromJson($response, 3);
 }
 public function getMessage($message)
 {
     // Make the HAL object.
     $self = $url = $this->app['url_generator']->generate('messages.view', ['message' => $message['id']]);
     $hal = new Hal($self);
     // Add a link to the author.
     $author_id = $this->app['users.repository']->findByUsername($message['author'])['id'];
     $author = $url = $this->app['url_generator']->generate('users.view', ['user' => $author_id]);
     $hal->addLink('author', $author);
     // Add a link to the parent, if any.
     if ($message['parent']) {
         $up = $url = $this->app['url_generator']->generate('messages.view', ['message' => $message['parent']]);
         $hal->addLink('up', $up);
     }
     // Strip the now-irrelevant data from the object and send it.
     unset($message['id'], $message['parent'], $message['author']);
     $hal->setData($message);
     return $hal;
 }
Esempio n. 10
0
 public function execute(Request $request, Response $response, callable $next = null)
 {
     $pathParams = $request->getAttribute('pathParams');
     $params = $request->getQueryParams();
     $body = $request->getParsedBody();
     $body = array_merge($body, $params);
     \Assert\Assertion::keyExists($pathParams, 'name');
     \Assert\Assertion::keyExists($pathParams, 'id');
     $collection = $pathParams['name'];
     $id = $pathParams['id'];
     $this->boot()->db->table($collection)->update(array($body['name'] => $body['value'], 'add_date' => date("Y-m-d H:i:s")), "`id` = {$id}");
     $item = $this->boot()->db->table($collection)->fetchRow("`id` = {$id}");
     $hal = new Hal("/collection/{$collection}/{$id}", $item->toArray());
     $response = $response->withBody($this->toStream($hal->asJson()));
     if ($next) {
         $response = $next($request, $response);
     }
     return $response;
 }
Esempio n. 11
0
 /**
  * {@inheritdoc}
  */
 public function getData()
 {
     $data = parent::getData();
     if (!isset($data['message'])) {
         $data['message'] = $this->message;
     }
     if ($this->logref !== null && !isset($data['@logref'])) {
         $data['@logref'] = $this->logref;
     }
     return $data;
 }
Esempio n. 12
0
 public function execute(Request $request, Response $response, callable $next = null)
 {
     $pathParams = $request->getAttribute('pathParams');
     $params = $request->getQueryParams();
     $body = $request->getBody();
     \Assert\Assertion::keyExists($pathParams, 'name');
     \Assert\Assertion::keyExists($pathParams, 'id');
     \Assert\Assertion::isJsonString($body);
     $collection = $pathParams['name'];
     $id = $pathParams['id'];
     $data = json_decode($body, true);
     $this->boot()->db->table($collection)->update($data, "`id` = {$id}");
     $item = $this->boot()->db->table($collection)->fetchRow("`id` = {$id}");
     $hal = new Hal("/collection/{$collection}/{$id}", $item->toArray());
     $response = $response->withBody($this->toStream($hal->asJson()));
     if ($next) {
         $response = $next($request, $response);
     }
     return $response;
 }
Esempio n. 13
0
 public static function fromException(\Exception $exception, $prettyPrint = true, $debug = false)
 {
     $statusCode = self::extractStatus($exception);
     $headers = self::extractHeaders($exception);
     $message = self::extractMessage($exception, $debug);
     if ($exception instanceof HalException) {
         $hal = $exception->getHal();
     } else {
         $hal = new Hal(null, ['message' => $message]);
     }
     $data = $hal->getData();
     if (!isset($data['message']) || '' === $data['message']) {
         if ($message) {
             $data['message'] = $message;
         } elseif (isset(Response::$statusTexts[$statusCode])) {
             $data['message'] = Response::$statusTexts[$statusCode];
         }
         $hal->setData($data);
     }
     return new static($hal, $statusCode, $headers, $prettyPrint);
 }
Esempio n. 14
0
 public function __construct(RestedServiceInterface $restedService, UrlGeneratorInterface $urlGenerator, ResourceInterface $resource, ContextInterface $context, $uri = null, array $data = [])
 {
     parent::__construct($uri, $data);
     $this->context = $context;
     $this->resource = $resource;
     $this->restedService = $restedService;
     $this->urlGenerator = $urlGenerator;
     if ($context->wantsMetadata() === false) {
         $uri = null;
     }
     $this->addLink('self', $uri);
 }
Esempio n. 15
0
 public function execute(Request $request, Response $response, callable $next = null)
 {
     try {
         $pathParams = $request->getAttribute('pathParams');
         \Assert\Assertion::keyExists($pathParams, 'name');
         $body = $request->getBody();
         \Assert\Assertion::isJsonString($body);
         $collection = $pathParams['name'];
         $data = json_decode($body, true);
         $id = $this->boot()->db->table($collection)->insert($data);
         $item = $this->boot()->db->table($collection)->fetchRow("`id` = {$id}");
         $hal = new Hal("/collection/{$collection}/{$id}", $item->toArray());
         $response = $response->withBody($this->toStream($hal->asJson()));
     } catch (\Exception $ex) {
         $problem = new \Crell\ApiProblem\ApiProblem($ex->getMessage(), $request->getUri()->getPath());
         $problem->setDetail($ex->getTraceAsString())->setStatus($ex->getCode());
         return $response->withStatus(500)->withBody($this->toStream($problem->asJson()));
     }
     if ($next) {
         $response = $next($request, $response);
     }
     return $response;
 }
Esempio n. 16
0
 private function appendErrors(Hal $hal, FormInterface $form)
 {
     $formPath = null;
     /* @var $error FormError */
     foreach ($form->getErrors() as $error) {
         $data = ['message' => $error->getMessage()];
         $origin = $error->getOrigin();
         if ($origin) {
             $currPath = $this->getPath($origin);
         } else {
             if (null === $formPath) {
                 $formPath = $this->getPath($form);
             }
             $currPath = $formPath;
         }
         if ($currPath) {
             $data['path'] = $currPath;
         }
         $hal->addResource('errors', new Hal(null, $data));
     }
     foreach ($form->all() as $child) {
         $this->appendErrors($hal, $child);
     }
 }
Esempio n. 17
0
    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $sample = <<<JSON
        {
            "id": 1,
            "name": "test",
            "_links":{
                "self":{"href":"http:\\/\\/127.0.0.1\\/2"},
                "prev":{"href":"http:\\/\\/127.0.0.1\\/1"},
                "next":{"href":"http:\\/\\/127.0.0.1\\/3"}
            },
            "_embedded":{
                "item":[
                    {
                        "_links":{
                            "self":{"href":"http:\\/\\/127.0.0.1\\/"},
                            "next":{"href":"http:\\/\\/127.0.0.1\\/3"}
                        },
                        "key": "value1"
                    },
                    {
                        "_links":{
                            "self":{"href":"http:\\/\\/127.0.0.1\\/"},
                            "next":{"href":"http:\\/\\/127.0.0.1\\/3"}
                        },
                        "key": "value2"
                    }
                ],
                "item2":[
                    {
                        "_links":{
                            "self":{"href":"http:\\/\\/127.0.0.1\\/"},
                            "next":{"href":"http:\\/\\/127.0.0.1\\/3"}
                        },
                        "key": "value1"
                    }
                ]
            }
        }
JSON;
        $this->object = new Resource(Hal::fromJson($sample, 2));
    }
Esempio n. 18
0
 public function execute(Request $request, Response $response, callable $next = null)
 {
     $pathParams = $request->getAttribute('pathParams');
     $queryParams = $request->getQueryParams();
     try {
         \Assert\Assertion::keyExists($pathParams, 'name');
         $collection = $pathParams['name'];
         $limit = $queryParams['limit'];
         $page = $queryParams['page'];
         $columns = $queryParams['columns'];
         $groups = $queryParams['groups'];
         $aggregates = $queryParams['aggregates'];
         $orders = $this->orders(isset($queryParams['orders']) ? $queryParams['orders'] : array());
         $wheres = $this->wheres(isset($queryParams['filters']) ? $queryParams['filters'] : array());
         $table = $this->boot()->db->table($collection);
         $paginator = $table->getPaginator($wheres, $orders, $limit, $page, $columns, $groups, $aggregates);
         $pages = (array) $paginator->getPages();
         $pages['requesttime'] = time();
         $pages['sql'] = $table->getSql();
         $query = http_build_query(['limit' => $pages['itemCountPerPage'], 'page' => $pages['current'], 'columns' => $queryParams['columns']]);
         $hal = new Hal("/collection/{$collection}?{$query}", $pages);
         $query = http_build_query(['limit' => $pages['itemCountPerPage'], 'page' => $pages['next'], 'columns' => $queryParams['columns']]);
         $hal->addLink('next', "/collection/{$collection}?{$query}");
         $query = http_build_query(['limit' => $pages['itemCountPerPage'], 'page' => $pages['previous'], 'columns' => $queryParams['columns']]);
         $hal->addLink('previous', "/collection/{$collection}?{$query}");
         $query = http_build_query(['limit' => $pages['itemCountPerPage'], 'page' => $pages['first'], 'columns' => $queryParams['columns']]);
         $hal->addLink('first', "/collection/{$collection}?{$query}");
         $query = http_build_query(['limit' => $pages['itemCountPerPage'], 'page' => $pages['last'], 'columns' => $queryParams['columns']]);
         $hal->addLink('last', "/collection/{$collection}?{$query}");
         foreach ($paginator as $item) {
             $resource = new Hal("/collection/{$collection}/{$item->id}", $item->toArray());
             $hal->addResource('items', $resource);
         }
     } catch (\Exception $ex) {
         $problem = new \Crell\ApiProblem\ApiProblem($ex->getMessage(), $request->getUri()->getPath());
         $problem->setDetail($ex->getTraceAsString())->setStatus($ex->getCode());
         return $response->withStatus(500)->withBody($this->toStream($problem->asJson()));
     }
     $response = $response->withHeader('Content-Type', 'application/json')->withBody($this->toStream($hal->asJson()));
     if ($next) {
         $response = $next($request, $response);
     }
     return $response;
 }
Esempio n. 19
0
 /**
  * Construtor.
  *
  * @param Zend\Http\Client   $client
  * @param Zend\Http\Response $response
  */
 public function __construct(ZendHttpClient $client, ZendHttpResponse $response, $depth = 0)
 {
     $this->httpClient = $client;
     $this->httpResponse = $response;
     if (!$this->httpResponse->isSuccess()) {
         $error = json_decode($this->httpResponse->getBody());
         if (empty($error)) {
             $error = new \stdClass();
             $error->status = $this->httpResponse->getStatusCode();
             $error->title = $this->httpResponse->getReasonPhrase();
             $error->detail = '';
         }
         if (!isset($error->status)) {
             $error->status = 500;
         }
         if (!isset($error->detail)) {
             $error->detail = 'An error occurred.';
         }
         throw new RuntimeException(json_encode($error, null, 100), $error->status);
     }
     if (!$this->httpResponse->getHeaders()->has('Content-Type')) {
         throw new RuntimeException("Missing 'Content-Type' header.", 500);
     }
     $contentType = $this->httpResponse->getHeaders()->get('Content-Type')->getFieldValue();
     $pos = strpos($contentType, ';');
     if ($pos !== false) {
         $contentType = substr($contentType, 0, $pos);
     }
     if (empty($this->httpResponse->getBody())) {
         $this->content = null;
     } elseif ($contentType == 'application/hal+json' || $contentType == 'application/json') {
         $this->content = new Resource(Hal::fromJson($this->httpResponse->getBody(), $depth));
     } elseif ($contentType == 'application/hal+xml' || $contentType == 'application/xml') {
         $this->content = new Resource(Hal::fromXml($this->httpResponse->getBody(), $depth));
     } else {
         throw new RuntimeException("Unable to handle content type '{$contentType}' for response: '{$this->httpResponse->getBody()}'.", 500);
     }
 }
Esempio n. 20
0
 /**
  * Get loaded data (including messages)
  *
  * @return array
  */
 public function getData()
 {
     $data = parent::getData();
     $data['_messages'] = $this->messages;
     return $data;
 }
Esempio n. 21
0
 /**
  * {@inheritdoc}
  *
  * We need to render the HAL object before we actually prepare the response.
  */
 public function prepare(Request $request)
 {
     $this->setContent($this->hal->asJson($this->pretty));
     return parent::prepare($request);
 }
Esempio n. 22
0
 /**
  * @covers Hermes\Api\Response::__construct
  */
 public function testAcceptXml()
 {
     $http = new Client();
     $response = new ZendResponse();
     $headers = new Headers();
     $headers->addHeaderLine('Content-Type', 'application/xml');
     $response->setHeaders($headers);
     $hal = Hal::fromJson(static::$sampleJson, 10);
     $xml = $hal->asXml(true);
     $response->setContent($xml);
     $this->object = new Response($http, $response);
     $content = $this->object->getContent();
     $this->assertInstanceOf(Resource::class, $content);
 }
Esempio n. 23
0
 public function __construct(Hal $resource)
 {
     $this->hal = $resource;
     $this->setPaginator($resource->getData());
 }
Esempio n. 24
0
 /**
  * {@inheritdoc}
  */
 public function done(Hal $response = null, $statusCode = HttpResponse::HTTP_OK, $headers = [])
 {
     $headers = array_merge(['content-type' => 'application/json'], $headers);
     $json = $response ? $response->asJson($this) : '';
     return new HttpResponse($json, $statusCode, $headers);
 }
Esempio n. 25
0
$data = array('first_name' => $given_name, 'middle_name' => $additional_name, 'last_name' => $family_name, 'email' => $email, 'location_type_id' => $location_type_id, 'street_address' => $postal_addresses, 'phone' => $phone, 'gender' => $gender);
//DELETE
if ($method == "DELETE") {
    header("HTTP/1.0 404 Not Found");
    echo "The person's record has been deleted successfully.";
    //ADD your SITE URL and KEYS here in the REST code below
    $ch = curl_init('<your CiviCRM site>/sites/all/modules/civicrm/extern/rest.php?entity=Contact&action=delete&json={"sequential":1,"id":' . $id . '}&api_key=yourkey&key=sitekey');
    curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Content-Type: application/json')));
    $response = curl_exec($ch);
    if ($response === FALSE) {
        die(curl_error($ch));
    }
} elseif ($method == "PUT") {
    //ADD your SITE URL and KEYS here in the REST code below
    $ch = curl_init('<your CiviCRM site>/sites/all/modules/civicrm/extern/rest.php?entity=Contact&action=create&json={"sequential":1,"id":' . $id . ',"contact_type":"Individual","first_name":"' . $given_name . '","middle_name":"' . $additional_name . '","last_name":"' . $family_name . '","gender_id":"' . $gender . '","api.Address.create":{"location_type_id":"' . $location_type_id . '","street_address":"' . $postal_addresses . '"},"api.Email.create":{"email":"' . $email . '"},"api.Phone.create":{"phone":' . $phone . '}}&api_key=yourkey&key=sitekey');
    curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_HEADER => FALSE, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS, http_build_query($data)));
    $response = curl_exec($ch);
    if ($response === FALSE) {
        die(curl_error($ch));
    }
}
//ADD your SITE URL and KEYS here in the REST code below
$json = file_get_contents('<your CiviCRM site>/sites/all/modules/civicrm/extern/rest.php?entity=People&action=get&json={"sequential":1,"id":' . $id . '}&api_key=yourkey&key=sitekey');
//ADD your SITE URL and KEYS here in the REST code below
$json3 = file_get_contents('<your CiviCRM site>/sites/all/modules/civicrm/extern/rest.php?entity=Address&action=get&json={"sequential":1,"id":' . $id . '}&api_key=yourkey&key=sitekey');
$array = json_decode($json, true);
$array3 = json_decode($json3, true);
foreach ($array['values'] as $key => $value) {
    $hal = new \Nocarrier\Hal('/sites/default/ext/org.civicrm.osdi/api/v3/People/person.php' . '?id=' . $id, ['given_name' => $array['values'][$key]['given_name'], 'family_name' => $array['values'][$key]['family_name'], 'email_addresses' => array(array('primary' => true, 'address' => $array['values'][$key]['email'])), 'identifiers' => array('civi_crm:' . $id), 'id' => $array['values'][$key]['contact_id'], 'created_date' => date("c", strtotime($array2['values'][$i]['created_date'])), 'modified_date' => date("c", strtotime($array2['values'][$i]['modified_date'])), 'custom_fields' => array(), 'postal_addresses' => array(array('address_lines' => array(array($array['values'][$key]['postal_addresses'])), 'locality' => $array['values'][$key]['city'], 'region' => $array['values'][$key]['state_province_name'], 'postal_code' => $array['values'][$key]['postal_code'], 'country' => array_search($array['values'][$key]['country'], $countrycodes), 'primary' => filter_var($array3['values'][$key]['is_primary'], FILTER_VALIDATE_BOOLEAN))), 'phone_numbers' => array(array('number' => $array['values'][$key]['number']))]);
}
echo $hal->asJson();
 /**
  * @param array $body
  * @param array $links
  * @param Hal   $hal
  *
  * @internal param Uri $uri
  */
 private function getHalLink(array $body, array $links, Hal $hal)
 {
     foreach ($links as $link) {
         if (!$link instanceof Link) {
             continue;
         }
         $uri = uri_template($link->href, $body);
         $reverseUri = $this->getReverseMatchedLink($uri);
         $hal->addLink($link->rel, $reverseUri);
     }
 }
Esempio n. 27
0
 public function testResourceWithNullSelfLinkRendersLinksInJson()
 {
     $x = new Hal(null);
     $x->addLink('testrel', 'http://test');
     $data = json_decode($x->asJson());
     $this->assertEquals('http://test', $data->_links->testrel->href);
 }
Esempio n. 28
0
 public function notFoundAction(Application $app, Request $request)
 {
     $response = new Hal($request->getRequestUri(), array("http status code" => 404, "http status description" => "Not Found", "message" => "document does not exist"));
     return new Response($response->asJson(), 404, array("Content-Type" => $app['request']->getMimeType('json')));
 }
Esempio n. 29
0
 /**
  * @param hal\Hal $hal
  *
  * @return string
  *
  * @codeCoverageIgnore
  */
 protected function _jsonEncode(hal\Hal $hal)
 {
     return $hal->asJson();
 }
 private function halResponse(Hal $resource)
 {
     return new Response($resource->asJson(true), 200, ['Content-Type' => 'application/hal+json']);
 }