Ejemplo n.º 1
0
    /**
     * Add a link
     *
     * @param  Link $link
     * @param  bool $overwrite
     * @return self
     * @throws Exception\DomainException
     */
    public function add(Link $link, $overwrite = false)
    {
        $relation = $link->getRelation();
        if (!isset($this->links[$relation]) || $overwrite || 'self' == $relation) {
            $this->links[$relation] = $link;
            return $this;
        }

        if ($this->links[$relation] instanceof Link) {
            $this->links[$relation] = array($this->links[$relation]);
        }

        if (!is_array($this->links[$relation])) {
            $type = (is_object($this->links[$relation])
                ? get_class($this->links[$relation])
                : gettype($this->links[$relation]));
            throw new Exception\DomainException(sprintf(
                '%s::$links should be either a %s\Link or an array; however, it is a "%s"',
                __CLASS__,
                __NAMESPACE__,
                $type
            ));
        }

        $this->links[$relation][] = $link;
        return $this;
    }
Ejemplo n.º 2
0
 /**
  * Attach download link to asset HAL metadata
  *
  * @param Event $event
  */
 public function attachAssetLink(Event $event)
 {
     $halEntity = $event->getParam('entity');
     $uri = $this->getServiceLocator()->get('Router')->getRequestUri();
     $link = new HalLink('download');
     $link->setUrl($uri->getScheme() . '://' . $uri->getHost() . '/' . $halEntity->entity->getBaseurl() . '/' . $halEntity->entity->getFilename());
     $halEntity->getLinks()->add($link);
 }
 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]];
 }
Ejemplo n.º 4
0
 private function createSelfLink($resource, $route, $routeIdentifier)
 {
     $link = new Link('self');
     $link->setRoute($route);
     $routeParams = $this->getRouteParams($resource, $routeIdentifier);
     if (!empty($routeParams)) {
         $link->setRouteParams($routeParams);
     }
     $routeOptions = $this->getRouteOptions($resource);
     if (!empty($routeOptions)) {
         $link->setRouteOptions($routeOptions);
     }
     return $link;
 }
 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));
 }
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
0
 /**
  * @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;
 }
 /**
  * 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;
 }
Ejemplo n.º 9
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;
 }
 public function onRenderEntity(EventManagerEvent $e)
 {
     $entity = $e->getParam('entity');
     if (!$entity->entity instanceof Pages) {
         return;
     }
     $entity->getLinks()->add(HalLink::factory(array('rel' => 'images', 'route' => array('name' => 'application.rest.images', 'params' => ['page_id' => $entity->entity->getUuid()]))));
 }
Ejemplo n.º 11
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),
        );
    }
Ejemplo n.º 12
0
 public function onRenderEntity($e)
 {
     $entity = $e->getParam('entity');
     /**
      * Attach a link to the revision entity data
      */
     if (!$entity->entity instanceof RevisionEntity) {
         // do nothing
         return;
     }
     $entity->getLinks()->add(\ZF\Hal\Link\Link::factory(array('rel' => 'revisionEntityData', 'route' => array('name' => 'zf.doctrine.audit.api.rpc.revision-entity-value', 'params' => array('revision_entity_id' => $entity->entity->getId())))));
 }
 public function extract($value)
 {
     $config = $this->getServiceManager()->get('Config');
     if (!method_exists($value, 'getTypeClass') || !isset($config['zf-hal']['metadata_map'][$value->getTypeClass()->name])) {
         return;
     }
     $config = $config['zf-hal']['metadata_map'][$value->getTypeClass()->name];
     $mapping = $value->getMapping();
     $filter = new FilterChain();
     $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower');
     $link = new Link($filter($mapping['fieldName']));
     $link->setRoute($config['route_name']);
     $link->setRouteParams(array('id' => null));
     if (isset($config['zf-doctrine-querybuilder-options']['filter_key'])) {
         $filterKey = $config['zf-doctrine-querybuilder-options']['filter_key'];
     } else {
         $filterKey = 'filter';
     }
     $link->setRouteOptions(array('query' => array($filterKey => array(array('field' => $mapping['mappedBy'], 'type' => 'eq', 'value' => $value->getOwner()->getId())))));
     return $link;
 }
 public function testLinkCollectionWithTwoLinksForSameRelationShouldReturnArrayWithOneKeyAggregatingLinks()
 {
     $linkCollection = new LinkCollection();
     $linkCollection->add(Link::factory(['rel' => 'foo', 'url' => 'http://example.com/foo']));
     $linkCollection->add(Link::factory(['rel' => 'foo', 'url' => 'http://example.com/bar']));
     $linkCollection->add(Link::factory(['rel' => 'baz', 'url' => 'http://example.com/baz']));
     $result = $this->linkCollectionExtractor->extract($linkCollection);
     $this->assertInternalType('array', $result);
     $this->assertCount(2, $result);
     $this->assertInternalType('array', $result['foo']);
     $this->assertCount(2, $result['foo']);
 }
 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]);
 }
Ejemplo n.º 17
0
 /**
  * @group 95
  */
 public function testPassingFalseReuseParamsOptionShouldOmitMatchedParametersInGeneratedLink()
 {
     $serverUrlHelper = $this->getMock('Zend\\View\\Helper\\ServerUrl');
     $urlHelper = new UrlHelper();
     $linkExtractor = new LinkExtractor($serverUrlHelper, $urlHelper);
     $match = $this->matchUrl('/resource/foo', $urlHelper);
     $this->assertEquals('foo', $match->getParam('id', false));
     $link = Link::factory(['rel' => 'resource', 'route' => ['name' => 'hostname/resource', 'options' => ['reuse_matched_params' => false]]]);
     $result = $linkExtractor->extract($link);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('href', $result);
     $this->assertEquals('http://localhost.localdomain/resource', $result['href']);
 }
Ejemplo n.º 18
0
 protected function injectThumbnailLinks($entity)
 {
     $config = $this->sm->get('Config');
     if (empty($config['file-manager']['thumbnail-types'])) {
         return [];
     }
     foreach ($config['file-manager']['thumbnail-types'] as $typeName => $type) {
         if (strpos($entity['mime_type'], 'image') === 0) {
             $entity['thumbnail_' . $typeName] = Link::factory(array('rel' => 'thumbnail_' . $typeName, 'route' => ['name' => 'kap-file-manager.rpc.file-thumbnail', 'params' => ['filter' => $type['filter'], 'width' => $type['width'], 'height' => $type['height'], 'file_id' => $entity['id']]]));
         } else {
             throw new \Exception("TODO what's thumbnail for {$entity['mime_type']}?");
         }
     }
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 20
0
 /**
  * @inheritDoc
  */
 public function extract(Link $object)
 {
     if (!$object->isComplete()) {
         throw new DomainException(sprintf('Link from resource provided to %s was incomplete; must contain a URL or a route', __METHOD__));
     }
     $representation = $object->getProps();
     if ($object->hasUrl()) {
         $representation['href'] = $object->getUrl();
         return $representation;
     }
     $reuseMatchedParams = true;
     $options = $object->getRouteOptions();
     if (isset($options['reuse_matched_params'])) {
         $reuseMatchedParams = (bool) $options['reuse_matched_params'];
         unset($options['reuse_matched_params']);
     }
     $representation['href'] = $this->linkUrlBuilder->buildLinkUrl($object->getRoute(), $object->getRouteParams(), $options, $reuseMatchedParams);
     return $representation;
 }
 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));
 }
Ejemplo n.º 22
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));
 }
Ejemplo n.º 24
0
 /**
  * @inheritDoc
  */
 public function extract(Link $object)
 {
     if (!$object->isComplete()) {
         throw new DomainException(sprintf('Link from resource provided to %s was incomplete; must contain a URL or a route', __METHOD__));
     }
     $representation = $object->getProps();
     if ($object->hasUrl()) {
         $representation['href'] = $object->getUrl();
         return $representation;
     }
     $reuseMatchedParams = true;
     $options = $object->getRouteOptions();
     if (isset($options['reuse_matched_params'])) {
         $reuseMatchedParams = (bool) $options['reuse_matched_params'];
         unset($options['reuse_matched_params']);
     }
     $path = call_user_func($this->urlHelper, $object->getRoute(), $object->getRouteParams(), $options, $reuseMatchedParams);
     if (substr($path, 0, 4) == 'http') {
         $representation['href'] = $path;
     } else {
         $representation['href'] = $this->getServerUrl() . $path;
     }
     return $representation;
 }
 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]);
 }
Ejemplo n.º 26
0
 /**
  * Extract a collection as an array
  *
  * @todo   Remove 'resource' from event parameters for 1.0.0
  * @todo   Remove trigger of 'renderCollection.resource' for 1.0.0
  * @param  Collection $halCollection
  * @param  int $depth                   depth of the current rendering recursion
  * @param  int $maxDepth                maximum rendering depth for the current metadata
  * @return array
  */
 protected function extractCollection(Collection $halCollection, $depth = 0, $maxDepth = null)
 {
     $collection = [];
     $events = $this->getEventManager();
     $routeIdentifierName = $halCollection->getRouteIdentifierName();
     $entityRoute = $halCollection->getEntityRoute();
     $entityRouteParams = $halCollection->getEntityRouteParams();
     $entityRouteOptions = $halCollection->getEntityRouteOptions();
     $metadataMap = $this->getMetadataMap();
     foreach ($halCollection->getCollection() as $entity) {
         $eventParams = new ArrayObject(['collection' => $halCollection, 'entity' => $entity, 'resource' => $entity, 'route' => $entityRoute, 'routeParams' => $entityRouteParams, 'routeOptions' => $entityRouteOptions]);
         $events->trigger('renderCollection.resource', $this, $eventParams);
         $events->trigger('renderCollection.entity', $this, $eventParams);
         $entity = $eventParams['entity'];
         if (is_object($entity) && $metadataMap->has($entity)) {
             $entity = $this->getResourceFactory()->createEntityFromMetadata($entity, $metadataMap->get($entity));
         }
         if ($entity instanceof Entity) {
             // Depth does not increment at this level
             $collection[] = $this->renderEntity($entity, $this->getRenderCollections(), $depth, $maxDepth);
             continue;
         }
         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));
             }
             if ($value instanceof Entity) {
                 $this->extractEmbeddedEntity($entity, $key, $value, $depth + 1, $maxDepth);
             }
             if ($value instanceof Collection) {
                 $this->extractEmbeddedCollection($entity, $key, $value, $depth + 1, $maxDepth);
             }
         }
         $id = $this->getIdFromEntity($entity);
         if ($id === false) {
             // Cannot handle entities without an identifier
             // Return as-is
             $collection[] = $entity;
             continue;
         }
         if ($eventParams['entity'] instanceof LinkCollectionAwareInterface) {
             $links = $eventParams['entity']->getLinks();
         } else {
             $links = new LinkCollection();
         }
         if (isset($entity['links']) && $entity['links'] instanceof LinkCollection) {
             $links = $entity['links'];
         }
         /* $entity is always an array here. We don't have metadata config for arrays so the self link is forced
            by default (at the moment) and should be removed manually if not required. But at some point it should
            be discussed if it makes sense to force self links in this particular use-case.  */
         $selfLink = new Link('self');
         $selfLink->setRoute($eventParams['route'], array_merge($eventParams['routeParams'], [$routeIdentifierName => $id]), $eventParams['routeOptions']);
         $links->add($selfLink);
         $entity['_links'] = $this->fromLinkCollection($links);
         $collection[] = $entity;
     }
     return $collection;
 }
 public function testAllowsSpecifyingAlternateCallbackForReturningEntityId()
 {
     $this->setUpHelpers();
     $this->helpers->get('Hal')->getEventManager()->attach('getIdFromEntity', function ($e) {
         $entity = $e->getParam('entity');
         if (!is_array($entity)) {
             return false;
         }
         if (array_key_exists('name', $entity)) {
             return $entity['name'];
         }
         return false;
     }, 10);
     $prototype = array('foo' => 'bar');
     $items = array();
     foreach (range(1, 100) as $id) {
         $item = $prototype;
         $item['name'] = $id;
         $items[] = $item;
     }
     $collection = new Collection($items);
     $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));
     $this->assertRelationalLinkEquals('http://localhost.localdomain/resource', 'self', $test);
     $this->assertObjectHasAttribute('_embedded', $test);
     $this->assertInstanceof('stdClass', $test->_embedded);
     $this->assertObjectHasAttribute('items', $test->_embedded);
     $this->assertInternalType('array', $test->_embedded->items);
     $this->assertEquals(100, count($test->_embedded->items));
     foreach ($test->_embedded->items as $key => $item) {
         $id = $key + 1;
         $this->assertRelationalLinkEquals('http://localhost.localdomain/resource/' . $id, 'self', $item);
         $this->assertObjectHasAttribute('name', $item, var_export($item, 1));
         $this->assertEquals($id, $item->name);
         $this->assertObjectHasAttribute('foo', $item);
         $this->assertEquals('bar', $item->foo);
     }
 }
 public function setUpChildCollection()
 {
     $children = array(array('luke', 'Luke Skywalker'), array('leia', 'Leia Organa'));
     $this->collection = array();
     foreach ($children as $info) {
         $collection[] = call_user_func_array(array($this, 'setUpChildResource'), $info);
     }
     $collection = new HalCollection($this->collection);
     $collection->setCollectionRoute('parent/child');
     $collection->setEntityRoute('parent/child');
     $collection->setPage(1);
     $collection->setPageSize(10);
     $collection->setCollectionName('child');
     $link = new Link('self');
     $link->setRoute('parent/child');
     $collection->getLinks()->add($link);
     return $collection;
 }
 public function injectEntitySelfLink($links, $route, $module, $controller, $inputFilterName)
 {
     $links->add(Link::factory(array('rel' => 'self', 'route' => array('name' => $route, 'params' => array('name' => $module, 'controller_service_name' => $controller, 'input_filter_name' => $inputFilterName)))));
 }
Ejemplo n.º 30
0
 /**
  * Inject service links
  *
  * @param  string $type "rpc" | "rest" | "authorization"
  * @param  array|\Traversable $services
  * @param  LinkCollection $links
  * @param  null|string $module
  */
 protected function injectLinksForServicesByType($type, $services, LinkCollection $links, $module = null)
 {
     $urlHelper = $this->urlHelper;
     $linkType = $type;
     if (in_array($type, array('rpc', 'rest'))) {
         $linkType .= '-service';
     }
     $routeName = sprintf('zf-apigility/api/module/%s', $linkType);
     $routeParams = array();
     $routeOptions = array();
     if (null !== $module) {
         $routeParams['name'] = $module;
     }
     $url = call_user_func($urlHelper, $routeName, $routeParams, $routeOptions, false);
     $url .= '{?version}';
     $spec = array('rel' => $type, 'url' => $url, 'props' => array('templated' => true));
     $link = Link::factory($spec);
     $links->add($link);
 }