/** * This function outputs the given $data as valid HAL+JSON to the client * and sets the HTTP Response Code to the given $statusCode. * * @param array|SlimBootstrap\DataObject $data The data to output to * the client * @param int $statusCode The status code to set * in the reponse */ public function write($data, $statusCode = 200) { $path = $this->_request->getPath(); $hal = new hal\Hal($path); if (true === is_array($data)) { $pathData = explode('/', $path); unset($pathData[0]); $endpointName = end($pathData); $endpointUri = '/' . implode('/', $pathData) . '/'; foreach ($data as $entry) { /** @var SlimBootstrap\DataObject $entry */ $identifiers = $entry->getIdentifiers(); $resourceName = $endpointUri . implode('/', array_values($identifiers)); $resource = new hal\Hal($resourceName, $entry->getData() + $entry->getIdentifiers()); $this->_addAdditionalLinks($resource, $entry->getLinks()); $hal->addLink($endpointName, $resourceName); $hal->addResource($endpointName, $resource); } } else { $hal->setData($data->getData() + $data->getIdentifiers()); $this->_addAdditionalLinks($hal, $data->getLinks()); } $body = $this->_jsonEncode($hal); if (false === $body) { $this->_response->setStatus(500); $this->_response->setBody("Error encoding requested data."); return; } $this->_headers->set('Content-Type', 'application/hal+json; charset=UTF-8'); $this->_response->setStatus($statusCode); $this->_response->setBody($hal->asJson()); }
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)); } }
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; }
/** * @Route("/stages", name="list_stages") */ public function listStagesAction() { $normalizer = $this->normalizer(); $stages = $this->getDoctrine()->getRepository("AppBundle:Stage")->findAll(); $hal = new Hal('/stages', ['total' => count($stages)]); foreach ($stages as $stage) { $hal->addResource('stages', (new Hal('/stages/' . $stage->getId()))->setData($normalizer->normalize($stage))); } return $this->halResponse($hal); }
/** * @Route("/categories", name="list_categories") */ public function listCategoriesAction() { $normalizer = $this->normalizer(); $categories = $this->getDoctrine()->getRepository("AppBundle:Category")->findBy([], ['position' => 'ASC']); $hal = new Hal('/categories', ['total' => count($categories)]); foreach ($categories as $category) { $hal->addResource('categories', (new Hal('/categories/' . $category->getId()))->setData($normalizer->normalize($category))); } return $this->halResponse($hal); }
/** * @Route("/providers", name="list_providers") */ public function listProvidersAction() { $normalizer = $this->normalizer(); $providers = $this->getDoctrine()->getRepository("AppBundle:Provider")->findAll(); $hal = new Hal('/providers', ['total' => count($providers)]); foreach ($providers as $provider) { $hal->addResource('providers', (new Hal('/providers/' . $provider->getId()))->setData($normalizer->normalize($provider))); } return $this->halResponse($hal); }
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; }
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; }
/** * @Route("/services", name="list_services") */ public function listServicesAction() { $em = $this->getDoctrine()->getManager(); $query = $em->createQuery(' SELECT s, p, st, c, su, i FROM AppBundle:Service s LEFT JOIN s.providers p LEFT JOIN s.stages st LEFT JOIN s.categories c LEFT JOIN s.serviceUsers su LEFT JOIN s.issues i WHERE s.hidden = 0 '); $services = $query->getResult(); $hal = new Hal('/services', ['total' => count($services)]); foreach ($services as $service) { $hal->addResource('services', $this->createServiceHal($service)); } return $this->halResponse($hal); }
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); } }
public function testXMLEmptyEmbeddedCollection() { $x = new Hal(); $x->addResource('collection'); $response = <<<EOD <?xml version="1.0"?> <resource><resource rel="collection"/></resource> EOD; $this->assertEquals($response, $x->asXml()); }
<?php header("Content-Type:application/hal+json"); include 'blank.php'; include 'country_codes.php'; //ADD your complete server root path here require_once '<your site root directory path>/sites/all/libraries/vendor/autoload.php'; use Nocarrier\Hal; $count = sizeof($array['values']); $hal = new \Nocarrier\Hal('/sites/default/ext/org.civicrm.osdi/api/v3/People/index.php', ['per_page' => $count, 'page' => 1, 'total_records' => $count]); foreach ($array['values'] as $key => $value) { $i = $array['values'][$key]['id']; $resource = new \Nocarrier\Hal('/People?contact_id=' . $array['values'][$key]['id'], array('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:' . $i), 'id' => $array['values'][$key]['id'], 'created_date' => date("c", strtotime($array2['values'][$i]['created_date'])), 'modified_date' => date("c", strtotime($array['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'])))); $resource->addLink('self', '/sites/default/ext/org.civicrm.osdi/api/v3/People/person.php' . '?id=' . $i); $hal->addResource('osdi-people', $resource); } $hal->addLink('next', '/sites/default/ext/org.civicrm.osdi/api/v3/People' . '?page=' . ($page + 1)); $hal->addLink('previous', '/sites/default/ext/org.civicrm.osdi/api/v3/People' . '?page=' . ($page - 1)); echo $hal->asJson();
public function testGetFirstResourceReturnsFirstOfMultipleItems() { $hal = new Hal('http://example.com/'); $res1 = new Hal('/resource/1', array('field1' => 'value1', 'field2' => 'value2')); $res2 = new Hal('/resource/2', array('field2' => 'value2', 'field2' => 'value2')); $hal->addResource('resource', $res1); $hal->addResource('resource', $res2); $this->assertEquals($res1, $hal->getFirstResource("resource")); }
public function testResourceWithListRendersCorrectlyInXmlResponse() { $hal = new Hal('/orders'); $hal->addLink('next', '/orders?page=2'); $hal->addLink('search', '/orders?id={order_id}'); $resource = new Hal('/orders/123', array('tests' => array(array('total' => 30.0, 'currency' => 'USD'), array('total' => 40.0, 'currency' => 'GBP')))); $resource->addLink('customer', '/customer/bob', 'Bob Jones <*****@*****.**>'); $hal->addResource('order', $resource); $result = new \SimpleXmlElement($hal->asXml()); $this->assertEquals(30, (string) $result->resource->tests[0]->total); $this->assertEquals('USD', (string) $result->resource->tests[0]->currency); $this->assertEquals(40, (string) $result->resource->tests[1]->total); $this->assertEquals('GBP', (string) $result->resource->tests[1]->currency); }