示例#1
0
 protected function build($key, $value)
 {
     $entity = new HalEntity(new GadgetEntity($value), $value->getId());
     $entity->getLinks()->add(Link::factory(['rel' => 'self', 'route' => ['name' => 'zource-application.rest.gadget', 'params' => ['gadget_id' => $value->getId()]]]));
     $entity->getLinks()->add(Link::factory(['rel' => 'gadget-container', 'route' => ['name' => 'zource-application.rest.gadget-container', 'params' => ['gadget_container_id' => $value->getGadgetContainer()->getId()]]]));
     return $entity;
 }
示例#2
0
 private function buildEntity($plugin)
 {
     $entity = new HalEntity(new PluginEntity($plugin), $plugin->getId());
     $entity->getLinks()->add(Link::factory(['rel' => 'activate', 'route' => ['name' => 'zource-application.rest.plugin', 'params' => ['plugin_id' => $plugin->getId()]]]));
     $entity->getLinks()->add(Link::factory(['rel' => 'deactivate', 'route' => ['name' => 'zource-application.rest.plugin', 'params' => ['plugin_id' => $plugin->getId()]]]));
     return $entity;
 }
 /**
  * @param  \ZB\Utils\Entity\IdProviderInterface $idProvider
  * @param  \ZF\Hal\Plugin\Hal $halPlugin
  * @return \ZF\Hal\Entity
  */
 public function convertToHalEntity(IdProviderInterface $idProvider, HalPlugin $halPlugin)
 {
     $halMetadata = $halPlugin->getMetadataMap()->get($idProvider);
     $halEntity = new HalEntity($idProvider);
     $halEntity->getLinks()->add(HalLink::factory(array('rel' => 'self', 'route' => array('name' => $halMetadata->getRoute(), 'options' => $halMetadata->getRouteOptions(), 'params' => array_merge($halMetadata->getRouteParams(), array($halMetadata->getRouteIdentifierName() => $idProvider->getId()))))));
     return $halEntity;
 }
 public function authenticationAction()
 {
     $request = $this->getRequest();
     switch ($request->getMethod()) {
         case $request::METHOD_GET:
             $entity = $this->model->fetch();
             if (!$entity) {
                 $response = $this->getResponse();
                 $response->setStatusCode(204);
                 return $response;
             }
             break;
         case $request::METHOD_POST:
             $entity = $this->model->create($this->bodyParams());
             $response = $this->getResponse();
             $response->setStatusCode(201);
             $response->getHeaders()->addHeaderLine('Location', $this->plugin('hal')->createLink($this->getRouteForEntity($entity)));
             break;
         case $request::METHOD_PATCH:
             $entity = $this->model->update($this->bodyParams());
             break;
         case $request::METHOD_DELETE:
             if ($this->model->remove()) {
                 return $this->getResponse()->setStatusCode(204);
             }
             return new ApiProblemResponse(new ApiProblem(404, 'No authentication configuration found'));
         default:
             return new ApiProblemResponse(new ApiProblem(405, 'Only the methods GET, POST, PATCH, and DELETE are allowed for this URI'));
     }
     $halEntity = new Entity($entity, null);
     $halEntity->getLinks()->add(Link::factory(array('rel' => 'self', 'route' => $this->getRouteForEntity($entity))));
     return new ViewModel(array('payload' => $halEntity));
 }
示例#5
0
 /**
  * Create a entity and/or collection based on a metadata map
  *
  * @param  object $object
  * @param  Metadata $metadata
  * @param  bool $renderEmbeddedEntities
  * @return Entity|Collection
  * @throws Exception\RuntimeException
  */
 public function createEntityFromMetadata($object, Metadata $metadata, $renderEmbeddedEntities = true)
 {
     if ($metadata->isCollection()) {
         return $this->createCollectionFromMetadata($object, $metadata);
     }
     $data = $this->entityExtractor->extract($object);
     $entityIdentifierName = $metadata->getEntityIdentifierName();
     if ($entityIdentifierName && !isset($data[$entityIdentifierName])) {
         throw new Exception\RuntimeException(sprintf('Unable to determine entity identifier for object of type "%s"; no fields matching "%s"', get_class($object), $entityIdentifierName));
     }
     $id = $entityIdentifierName ? $data[$entityIdentifierName] : null;
     if (!$renderEmbeddedEntities) {
         if ($id) {
             $object = ['id' => $id];
         } else {
             $object = [];
         }
     }
     $halEntity = new Entity($object, $id);
     $links = $halEntity->getLinks();
     $this->marshalMetadataLinks($metadata, $links);
     $forceSelfLink = $metadata->getForceSelfLink();
     if ($forceSelfLink && !$links->has('self')) {
         $link = $this->marshalLinkFromMetadata($metadata, $object, $id, $metadata->getRouteIdentifierName());
         $links->add($link);
     }
     return $halEntity;
 }
示例#6
0
 public function testLinkCollectionMayBeInjected()
 {
     $entity = new stdClass;
     $hal    = new Entity($entity, 'id', 'route', array('foo' => 'bar'));
     $links  = new LinkCollection();
     $hal->setLinks($links);
     $this->assertSame($links, $hal->getLinks());
 }
 public function setUpChildEntity($id, $name)
 {
     $this->child = (object) array('id' => $id, 'name' => $name);
     $entity = new Entity($this->child, $id);
     $link = new Link('self');
     $link->setRoute('parent/child');
     $link->setRouteParams(array('child' => $id));
     $entity->getLinks()->add($link);
     return $entity;
 }
 public function halObjects()
 {
     $entity = new Entity(['foo' => 'bar'], 'identifier', 'route');
     $link = new Link('self');
     $link->setRoute('resource/route')->setRouteParams(['id' => 'identifier']);
     $entity->getLinks()->add($link);
     $collection = new Collection([$entity]);
     $collection->setCollectionRoute('collection/route');
     $collection->setEntityRoute('resource/route');
     return ['entity' => [$entity], 'collection' => [$collection]];
 }
示例#9
0
 public function testInjectEntitySelfLinkWithIdentifierShouldAddSelfLinkWithIdentifierRouteParam()
 {
     $routeIdentifier = 'id';
     $linkCollection = new LinkCollection();
     $resource = new Entity([], 123);
     $resource->setLinks($linkCollection);
     $injector = new SelfLinkInjector();
     $injector->injectSelfLink($resource, 'foo', $routeIdentifier);
     $this->assertTrue($linkCollection->has('self'));
     $selfLink = $linkCollection->get('self');
     $linkRouteParams = $selfLink->getRouteParams();
     $this->assertArrayHasKey($routeIdentifier, $linkRouteParams);
 }
 /**
  * Return a HAL entity with just a self link
  */
 public function extract($value)
 {
     if (is_null($value)) {
         return $value;
     }
     $entityValues = $this->getHydratorForEntity($value)->extract($value);
     $entityMetadata = $this->getMetadataMap()[ClassUtils::getRealClass(get_class($value))];
     $link = new Link('self');
     $link->setRoute($entityMetadata['route_name']);
     $link->setRouteParams(array($entityMetadata['route_identifier_name'] => $entityValues[$entityMetadata['entity_identifier_name']]));
     $linkCollection = new LinkCollection();
     $linkCollection->add($link);
     $halEntity = new HalEntity(new stdClass());
     $halEntity->setLinks($linkCollection);
     return $halEntity;
 }
 public function settingsDashboardAction()
 {
     $authentication = $this->authentication->fetch();
     if ($authentication) {
         $authenticationEntity = $authentication;
         $authentication = new Entity($authentication, null);
         $authentication->getLinks()->add(Link::factory(array('rel' => 'self', 'route' => $this->getRouteForEntity($authenticationEntity))));
     }
     $dbAdapters = new Collection($this->dbAdapters->fetchAll());
     $dbAdapters->setCollectionRoute('zf-apigility/api/db-adapter');
     $contentNegotiation = new Collection($this->contentNegotiation->fetchAll());
     $contentNegotiation->setCollectionRoute('zf-apigility/api/content-negotiation');
     $dashboard = array('authentication' => $authentication, 'content_negotiation' => $contentNegotiation, 'db_adapter' => $dbAdapters);
     $entity = new Entity($dashboard, 'settings-dashboard');
     $links = $entity->getLinks();
     $links->add(Link::factory(array('rel' => 'self', 'route' => array('name' => 'zf-apigility/api/settings-dashboard'))));
     return new ViewModel(array('payload' => $entity));
 }
示例#12
0
    public function halObjects()
    {
        $entity = new Entity(array(
            'foo' => 'bar',
        ), 'identifier', 'route');
        $link = new Link('self');
        $link->setRoute('resource/route')->setRouteParams(array('id' => 'identifier'));
        $entity->getLinks()->add($link);

        $collection = new Collection(array($entity));
        $collection->setCollectionRoute('collection/route');
        $collection->setEntityRoute('resource/route');

        return array(
            'entity'     => array($entity),
            'collection' => array($collection),
        );
    }
示例#13
0
    public function apiEnableAction()
    {
        $request = $this->getRequest();

        switch ($request->getMethod()) {

            case $request::METHOD_PUT:
                $module = $this->bodyParam('module', false);
                if (!$module) {
                    return new ApiProblemResponse(
                        new ApiProblem(
                            422,
                            'Module parameter not provided',
                            'https://tools.ietf.org/html/rfc4918',
                            'Unprocessable Entity'
                        )
                    );
                }

                $result = $this->moduleModel->updateModule($module);

                if (!$result) {
                    return new ApiProblemResponse(
                        new ApiProblem(500, 'Unable to Apigilify the module')
                    );
                }

                $metadata = new ModuleEntity($module);
                $entity   = new Entity($metadata, $module);
                $entity->getLinks()->add(Link::factory(array(
                    'rel'   => 'self',
                    'route' => array(
                        'name'   => 'zf-apigility/api/module',
                        'params' => array('module' => $module),
                    ),
                )));
                return new ViewModel(array('payload' => $entity));

            default:
                return new ApiProblemResponse(
                    new ApiProblem(405, 'Only the method PUT is allowed for this URI')
                );
        }
    }
 public function authorizationAction()
 {
     $request = $this->getRequest();
     $version = $request->getQuery('version', 1);
     $model = $this->getModel();
     switch ($request->getMethod()) {
         case $request::METHOD_GET:
             $entity = $model->fetch($version);
             break;
         case $request::METHOD_PUT:
             $entity = $model->update($this->bodyParams(), $version);
             break;
         default:
             return new ApiProblemResponse(new ApiProblem(405, 'Only the methods GET and PUT are allowed for this URI'));
     }
     $entity = new Entity($entity, null);
     $entity->getLinks()->add(Link::factory(array('rel' => 'self', 'route' => array('name' => 'zf-apigility/api/module/authorization', 'params' => array('name' => $this->moduleName), 'options' => array('query' => array('version' => $version))))));
     return new ViewModel(array('payload' => $entity));
 }
 public function setUpChildResource($id, $name)
 {
     $this->child = (object) ['id' => $id, 'name' => $name];
     $resource = new HalEntity($this->child, $id);
     $link = new Link('self');
     $link->setRoute('parent/child');
     $link->setRouteParams(['child' => $id]);
     $resource->getLinks()->add($link);
     return $resource;
 }
 public function extract($value)
 {
     if (!method_exists($value, 'getTypeClass')) {
         return;
     }
     $config = $this->getMetadataMap()[$value->getTypeClass()->name];
     $filter = new FilterChain();
     $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower');
     // Better way to create mapping name?
     // FIXME: use zf-hal collection_name
     $link = new Link('self');
     $link->setRoute($config['route_name']);
     $link->setRouteParams(array('id' => null));
     $filterValue = array('field' => $value->getMapping()['mappedBy'] ?: $value->getMapping()['inversedBy'], 'type' => isset($value->getMapping()['joinTable']) ? 'ismemberof' : 'eq', 'value' => $value->getOwner()->getId());
     $link->setRouteOptions(array('query' => array($this->getFilterKey() => array($filterValue))));
     $linkCollection = new LinkCollection();
     $linkCollection->add($link);
     $halEntity = new HalEntity(new stdClass());
     $halEntity->setLinks($linkCollection);
     return $halEntity;
 }
 public function indexAction()
 {
     $request = $this->getRequest();
     $httpMethod = $request->getMethod();
     $module = $this->params()->fromRoute('name', false);
     $controllerServiceName = $this->params()->fromRoute('controller_service_name', false);
     $controllerType = $this->params()->fromRoute('controller_type');
     // rest or rpc
     $routeName = $this->deriveRouteName($this->getEvent()->getRouteMatch()->getMatchedRouteName());
     switch ($httpMethod) {
         case HttpRequest::METHOD_GET:
             $result = new HalEntity($this->model->fetchDocumentation($module, $controllerServiceName), 'documentation');
             $self = new HalLink('self');
             $self->setRoute($routeName);
             $result->getLinks()->add($self);
             break;
         case HttpRequest::METHOD_PUT:
             $documentation = $this->bodyParams();
             $result = new HalEntity($this->model->storeDocumentation($module, $controllerType, $controllerServiceName, $documentation, true), 'documentation');
             $self = new HalLink('self');
             $self->setRoute($routeName);
             $result->getLinks()->add($self);
             break;
         case HttpRequest::METHOD_PATCH:
             $documentation = $this->bodyParams();
             $result = new HalEntity($this->model->storeDocumentation($module, $controllerType, $controllerServiceName, $documentation, false), 'documentation');
             $self = new HalLink('self');
             $self->setRoute($routeName);
             $result->getLinks()->add($self);
             break;
         case HttpRequest::METHOD_DELETE:
         case HttpRequest::METHOD_POST:
         default:
             return new ApiProblemResponse(new ApiProblem(404, 'Unsupported method.'));
     }
     $e = $this->getEvent();
     $e->setParam('ZFContentNegotiationFallback', 'HalJson');
     return new ViewModel(['payload' => $result]);
 }
 public function authorizationAction()
 {
     $request = $this->getRequest();
     $version = $request->getQuery('version', 1);
     $model = $this->getModel();
     switch ($request->getMethod()) {
         case $request::METHOD_GET:
             $entity = $model->fetch($version);
             break;
         case $request::METHOD_PUT:
             $this->getResponse()->getHeaders()->addHeaderLine('X-Deprecated', 'This service has deprecated the PUT method; please use PATCH');
             // intentionally fall through
         // intentionally fall through
         case $request::METHOD_PATCH:
             $entity = $model->update($this->bodyParams(), $version);
             break;
         default:
             return new ApiProblemResponse(new ApiProblem(405, 'Only the methods GET and PUT are allowed for this URI'));
     }
     $entity = new Entity($entity, null);
     $entity->getLinks()->add(Link::factory(['rel' => 'self', 'route' => ['name' => 'zf-apigility/api/module/authorization', 'params' => ['name' => $this->moduleName], 'options' => ['query' => ['version' => $version]]]]));
     return new ViewModel(['payload' => $entity]);
 }
示例#19
0
 /**
  * Fetch a resource
  *
  * @param  mixed $id
  * @return ApiProblem|mixed
  */
 public function fetch($id)
 {
     $stream = $this->streamService->fetch($id);
     $streamOwner = $this->streamService->fetchOwner($id);
     if (!$stream) {
         $entity = new Entity(array(), $id);
     } else {
         if ($streamOwner) {
             $channel = $this->channelService->fetch($streamOwner->channel_id);
             $stream->channel = $channel;
             unset($stream->channel_id);
         }
         $entity = new Entity($stream, $id);
     }
     if ($streamOwner) {
         $channelLink = new Link("channel");
         $channelLink->setUrl("/channel/" . $streamOwner->channel_id);
         $entity->getLinks()->add($channelLink);
         $userLink = new Link("user");
         $userLink->setUrl("/user/" . $streamOwner->user_id);
         $entity->getLinks()->add($userLink);
     }
     return $entity;
 }
示例#20
0
 /**
  * Render an individual entity
  *
  * Creates a hash representation of the Entity. The entity is first
  * converted to an array, and its associated links are injected as the
  * "_links" member. If any members of the entity are themselves
  * Entity objects, they are extracted into an "_embedded" hash.
  *
  * @param  Entity $halEntity
  * @param  bool $renderEntity
  * @param  int $depth           depth of the current rendering recursion
  * @param  int $maxDepth        maximum rendering depth for the current metadata
  * @throws Exception\CircularReferenceException
  * @return array
  */
 public function renderEntity(Entity $halEntity, $renderEntity = true, $depth = 0, $maxDepth = null)
 {
     $this->getEventManager()->trigger(__FUNCTION__, $this, ['entity' => $halEntity]);
     $entity = $halEntity->entity;
     $entityLinks = clone $halEntity->getLinks();
     // Clone to prevent link duplication
     $metadataMap = $this->getMetadataMap();
     if (is_object($entity)) {
         if ($maxDepth === null && $metadataMap->has($entity)) {
             $maxDepth = $metadataMap->get($entity)->getMaxDepth();
         }
         if ($maxDepth === null) {
             $entityHash = spl_object_hash($entity);
             if (isset($this->entityHashStack[$entityHash])) {
                 // we need to clear the stack, as the exception may be caught and the plugin may be invoked again
                 $this->entityHashStack = [];
                 throw new Exception\CircularReferenceException(sprintf("Circular reference detected in '%s'. %s", get_class($entity), "Either set a 'max_depth' metadata attribute or remove the reference"));
             }
             $this->entityHashStack[$entityHash] = get_class($entity);
         }
     }
     if (!$renderEntity || $maxDepth !== null && $depth > $maxDepth) {
         $entity = [];
     }
     if (!is_array($entity)) {
         $entity = $this->getEntityExtractor()->extract($entity);
     }
     foreach ($entity as $key => $value) {
         if (is_object($value) && $metadataMap->has($value)) {
             $value = $this->getResourceFactory()->createEntityFromMetadata($value, $metadataMap->get($value), $this->getRenderEmbeddedEntities());
         }
         if ($value instanceof Entity) {
             $this->extractEmbeddedEntity($entity, $key, $value, $depth + 1, $maxDepth);
         }
         if ($value instanceof Collection) {
             $this->extractEmbeddedCollection($entity, $key, $value, $depth + 1, $maxDepth);
         }
         if ($value instanceof Link) {
             // We have a link; add it to the entity if it's not already present.
             $entityLinks = $this->injectPropertyAsLink($value, $entityLinks);
             unset($entity[$key]);
         }
         if ($value instanceof LinkCollection) {
             foreach ($value as $link) {
                 $entityLinks = $this->injectPropertyAsLink($link, $entityLinks);
             }
             unset($entity[$key]);
         }
     }
     $halEntity->setLinks($entityLinks);
     $entity['_links'] = $this->fromResource($halEntity);
     $payload = new ArrayObject($entity);
     $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, ['payload' => $payload, 'entity' => $halEntity]);
     if (isset($entityHash)) {
         unset($this->entityHashStack[$entityHash]);
     }
     return $payload->getArrayCopy();
 }
 public function testRendersEmbeddedEntitiesOfIndividualPaginatedCollections()
 {
     $this->setUpHelpers();
     $this->router->addRoute('user', new Segment('/user[/:id]'));
     $child = new Entity(array('id' => 'matthew', 'name' => 'matthew', 'github' => 'weierophinney'), 'matthew', 'user');
     $link = new Link('self');
     $link->setRoute('user')->setRouteParams(array('id' => 'matthew'));
     $child->getLinks()->add($link);
     $prototype = array('foo' => 'bar', 'user' => $child);
     $items = array();
     foreach (range(1, 3) as $id) {
         $item = $prototype;
         $item['id'] = $id;
         $items[] = $item;
     }
     $adapter = new ArrayAdapter($items);
     $paginator = new Paginator($adapter);
     $collection = new Collection($paginator);
     $collection->setPageSize(5);
     $collection->setPage(1);
     $collection->setCollectionRoute('resource');
     $collection->setEntityRoute('resource');
     $links = $collection->getLinks();
     $self = new Link('self');
     $self->setRoute('resource');
     $links->add($self);
     $model = new HalJsonModel(array('payload' => $collection));
     $test = $this->renderer->render($model);
     $test = json_decode($test);
     $this->assertInstanceof('stdClass', $test, var_export($test, 1));
     $collection = $test->_embedded->items;
     foreach ($collection as $item) {
         $this->assertObjectHasAttribute('_embedded', $item, var_export($item, 1));
         $embedded = $item->_embedded;
         $this->assertObjectHasAttribute('user', $embedded);
         $user = $embedded->user;
         $this->assertRelationalLinkContains('/user/matthew', 'self', $user);
         $user = (array) $user;
         foreach ($child->entity as $key => $value) {
             $this->assertArrayHasKey($key, $user);
             $this->assertEquals($value, $user[$key]);
         }
     }
 }
 public function indexAction()
 {
     $event = $this->getEvent();
     $routeMatch = $event->getRouteMatch();
     $route = $this->deriveRouteName($routeMatch->getMatchedRouteName());
     $request = $this->getRequest();
     $module = $this->params()->fromRoute('name', false);
     $controller = $this->params()->fromRoute('controller_service_name', false);
     $inputFilterName = $this->params()->fromRoute('input_filter_name', false);
     if (!$module || !$this->model->moduleExists($module)) {
         return new ApiProblemResponse(new ApiProblem(404, 'The module specified does not exist'));
     }
     if (!$controller || !$this->model->controllerExists($module, $controller)) {
         return new ApiProblemResponse(new ApiProblem(404, 'The controller specified does not exist'));
     }
     switch ($request->getMethod()) {
         case $request::METHOD_GET:
             $result = $this->model->fetch($module, $controller, $inputFilterName);
             if (false === $result) {
                 return new ApiProblemResponse(new ApiProblem(404, 'The input filter specified does not exist'));
             }
             if ($result instanceof InputFilterCollection) {
                 $result = new HalCollection($result);
                 $result->setCollectionName('input_filter');
                 $result->getLinks()->add(Link::factory(array('rel' => 'self', 'route' => array('name' => $route, 'params' => array('name' => $module, 'controller_service_name' => str_replace('\\', '-', $controller))))));
                 $result->setEntityRoute($route);
                 break;
             }
             $name = $result['input_filter_name'];
             $result = new HalEntity($result, $name);
             $this->injectEntitySelfLink($result->getLinks(), $route, $module, $controller, $name);
             break;
         case $request::METHOD_POST:
             if ($inputFilterName) {
                 return new ApiProblemResponse(new ApiProblem(400, 'POST requests are not allowed to individual input filters'));
             }
             // Intentionally not breaking, as remainder of logic remains the same as PUT
         // Intentionally not breaking, as remainder of logic remains the same as PUT
         case $request::METHOD_PUT:
             $inputFilter = $this->bodyParams();
             $result = $this->model->update($module, $controller, $inputFilter);
             if (!$result) {
                 return new ApiProblemResponse(new ApiProblem(500, 'There was an unexpected error updating the input filter; please verify the module and controller specified are valid'));
             }
             $name = $result['input_filter_name'];
             $result = new HalEntity($result, $name);
             $this->injectEntitySelfLink($result->getLinks(), $route, $module, $controller, $name);
             break;
         case $request::METHOD_DELETE:
             if (empty($inputFilterName)) {
                 return new ApiProblemResponse(new ApiProblem(400, 'The input filter name has not been specified'));
             }
             $result = $this->model->remove($module, $controller, $inputFilterName);
             if (!$result) {
                 return new ApiProblemResponse(new ApiProblem(404, 'The input filter specified does not exist'));
             }
             return $this->getResponse()->setStatusCode(204);
     }
     $e = $this->getEvent();
     $e->setParam('ZFContentNegotiationFallback', 'HalJson');
     return new ViewModel(array('payload' => $result));
 }
示例#23
0
 public function injectServiceCollectionRelationalLinks($entity, $e)
 {
     $entity->exchangeArray(array('controller_service_name' => str_replace('\\', '-', $entity->controllerServiceName)));
     $module = $this->mvcEvent->getRouteMatch()->getParam('name');
     $service = $entity->controllerServiceName;
     $type = $this->getServiceType($service);
     $halEntity = new Entity($entity, $service);
     $links = $halEntity->getLinks();
     // Need to inject the self relational link, as otherwise the HAL plugin
     // sees we have links, and does not inject one.
     $links->add(Link::factory(array('rel' => 'self', 'route' => array('name' => sprintf('zf-apigility/api/module/%s-service', $type), 'params' => array('name' => $module, 'controller_service_name' => $service)))));
     // Add the input_filter relational link
     $links->add(Link::factory(array('rel' => 'input_filter', 'route' => array('name' => sprintf('zf-apigility/api/module/%s-service/input-filter', $type), 'params' => array('name' => $module, 'controller_service_name' => $service)))));
     // Add the documentation relational link
     $links->add(Link::factory(array('rel' => 'documentation', 'route' => array('name' => sprintf('zf-apigility/api/module/%s-service/doc', $type), 'params' => array('name' => $module, 'controller_service_name' => $service)))));
     $e->setParam('entity', $halEntity);
 }
 /**
  * Create and return an entity view model
  *
  * @param mixed $entity
  * @return ViewModel
  */
 private function createEntity($entity)
 {
     $halEntity = new Entity($entity, 'name');
     $halEntity->getLinks()->add(Link::factory(['rel' => 'self', 'route' => ['name' => 'zf-apigility/api/authentication', 'params' => ['authentication_adapter' => $entity['name']]]]));
     return new ViewModel(['payload' => $halEntity]);
 }
示例#25
0
 public function testRendersEmbeddedEntitiesOfIndividualPaginatedCollections()
 {
     $this->router->addRoute('user', new Segment('/user[/:id]'));
     $child = new Entity(['id' => 'matthew', 'name' => 'matthew', 'github' => 'weierophinney'], 'matthew');
     $link = new Link('self');
     $link->setRoute('user')->setRouteParams(['id' => 'matthew']);
     $child->getLinks()->add($link);
     $prototype = ['foo' => 'bar', 'user' => $child];
     $items = [];
     foreach (range(1, 3) as $id) {
         $item = $prototype;
         $item['id'] = $id;
         $items[] = $item;
     }
     $adapter = new ArrayPaginator($items);
     $paginator = new Paginator($adapter);
     $collection = new Collection($paginator);
     $collection->setPageSize(5);
     $collection->setPage(1);
     $collection->setCollectionRoute('resource');
     $collection->setEntityRoute('resource');
     $links = $collection->getLinks();
     $self = new Link('self');
     $self->setRoute('resource');
     $links->add($self);
     $result = $this->plugin->renderCollection($collection);
     $this->assertInternalType('array', $result, var_export($result, 1));
     $collection = $result['_embedded']['items'];
     foreach ($collection as $item) {
         $this->assertArrayHasKey('_embedded', $item, var_export($item, 1));
         $embedded = $item['_embedded'];
         $this->assertArrayHasKey('user', $embedded);
         $user = $embedded['user'];
         $this->assertRelationalLinkContains('/user/matthew', 'self', $user);
         foreach ($child->entity as $key => $value) {
             $this->assertArrayHasKey($key, $user);
             $this->assertEquals($value, $user[$key]);
         }
     }
 }
 /**
  * @group 79
  */
 public function testCreateHalEntityDoesNotInjectExistingEntityWithSelfRelationalLinkIfAlreadyPresent()
 {
     $entity = ['id' => 1, 'foo' => 'bar'];
     $halEntity = new HalEntity($entity, 1);
     $self = Link::factory(['rel' => 'self', 'url' => 'http://example.com/foo/1']);
     $halEntity->getLinks()->add($self);
     $r = new ReflectionMethod($this->controller, 'createHalEntity');
     $r->setAccessible(true);
     $result = $r->invoke($this->controller, $halEntity);
     $this->assertSame($result, $halEntity);
     $this->assertTrue($result->getLinks()->has('self'));
     $this->assertSame($self, $result->getLinks()->get('self'));
 }
示例#27
0
 /**
  * @group 101
  */
 public function testNotExistingRouteInMetadataLinks()
 {
     $object = new TestAsset\Entity('foo', 'Foo');
     $object->first_child = new TestAsset\EmbeddedEntity('bar', 'Bar');
     $entity = new Entity($object, 'foo');
     $self = new Link('self');
     $self->setRoute('hostname/resource', ['id' => 'foo']);
     $entity->getLinks()->add($self);
     $metadata = new MetadataMap(['ZFTest\\Hal\\Plugin\\TestAsset\\EmbeddedEntity' => ['hydrator' => 'Zend\\Hydrator\\ObjectProperty', 'route' => 'hostname/embedded', 'route_identifier_name' => 'id', 'entity_identifier_name' => 'id', 'links' => ['link' => ['rel' => 'link', 'route' => ['name' => 'non_existing_route']]]]]);
     $this->plugin->setMetadataMap($metadata);
     $expectedExceptionClass = class_exists(V2RouterException\RuntimeException::class) ? V2RouterException\RuntimeException::class : RouterException\RuntimeException::class;
     $this->setExpectedException($expectedExceptionClass);
     $this->plugin->renderEntity($entity);
 }
示例#28
0
 /**
  * Create an Entity instance and inject it with a self relational link if necessary
  *
  * @param  Entity|array|object $entity
  * @param  string $route
  * @param  string $routeIdentifierName
  * @return Entity
  */
 public function createEntity($entity, $route, $routeIdentifierName)
 {
     $metadataMap = $this->getMetadataMap();
     switch (true) {
         case is_object($entity) && $metadataMap->has($entity):
             $generatedEntity = $this->createEntityFromMetadata($entity, $metadataMap->get($entity));
             $halEntity = new Entity($entity, $generatedEntity->id);
             $halEntity->setLinks($generatedEntity->getLinks());
             break;
         case !$entity instanceof Entity:
             $id = $this->getIdFromEntity($entity) ?: null;
             $halEntity = new Entity($entity, $id);
             break;
         case $entity instanceof Entity:
         default:
             $halEntity = $entity;
             // as is
             break;
     }
     $metadata = !is_array($entity) && $metadataMap->has($entity) ? $metadataMap->get($entity) : false;
     if (!$metadata || $metadata && $metadata->getForceSelfLink()) {
         $this->injectSelfLink($halEntity, $route, $routeIdentifierName);
     }
     return $halEntity;
 }
示例#29
0
    protected function createNestedEntity()
    {
        $object = new TestAsset\Entity('foo', 'Foo');
        $object->first_child  = new TestAsset\EmbeddedEntityWithBackReference('bar', $object);
        $entity = new Entity($object, 'foo');
        $self = new Link('self');
        $self->setRoute('hostname/resource', array('id' => 'foo'));
        $entity->getLinks()->add($self);

        return $entity;
    }
 /**
  * Inject the input filters collection, if any, as an embedded collection
  *
  * @param RestServiceEntity $service
  */
 protected function injectInputFilters(RestServiceEntity $service)
 {
     $inputFilters = $this->inputFilterModel->fetch($this->moduleName, $service->controllerServiceName);
     if (!$inputFilters instanceof InputFilterCollection || !count($inputFilters)) {
         return;
     }
     $collection = [];
     $parentName = str_replace('\\', '-', $service->controllerServiceName);
     foreach ($inputFilters as $inputFilter) {
         $inputFilter['input_filter_name'] = str_replace('\\', '-', $inputFilter['input_filter_name']);
         $entity = new HalEntity($inputFilter, $inputFilter['input_filter_name']);
         $links = $entity->getLinks();
         $links->add(Link::factory(['rel' => 'self', 'route' => ['name' => 'zf-apigility/api/module/rest-service/input-filter', 'params' => ['name' => $this->moduleName, 'controller_service_name' => $parentName, 'input_filter_name' => $inputFilter['input_filter_name']]]]));
         $collection[] = $entity;
     }
     $collection = new HalCollection($collection);
     $collection->setCollectionName('input_filter');
     $collection->setCollectionRoute('zf-apigility/module/rest-service/input-filter');
     $collection->setCollectionRouteParams(['name' => $service->module, 'controller_service_name' => $service->controllerServiceName]);
     $service->exchangeArray(['input_filters' => $collection]);
 }