/** * Creates a link object, given metadata and a resource * * @param Metadata $metadata * @param object $object * @param null|string $id * @param null|string $routeIdentifierName * @param string $relation * @return Link * @throws Exception\RuntimeException */ public function marshalLinkFromMetadata(Metadata $metadata, $object, $id = null, $routeIdentifierName = null, $relation = 'self') { $link = new Link($relation); if ($metadata->hasUrl()) { $link->setUrl($metadata->getUrl()); return $link; } if (!$metadata->hasRoute()) { throw new Exception\RuntimeException(sprintf('Unable to create a self link for resource of type "%s"; metadata does not contain a route or a url', get_class($object))); } $params = $metadata->getRouteParams(); // process any callbacks foreach ($params as $key => $param) { // bind to the object if supported if ($param instanceof Closure && version_compare(PHP_VERSION, '5.4.0') >= 0) { $param = $param->bindTo($object); } // pass the object for callbacks and non-bound closures if (is_callable($param)) { $params[$key] = call_user_func_array($param, [$object]); } } if ($routeIdentifierName) { $params = array_merge($params, [$routeIdentifierName => $id]); } if ($relation !== 'self' && $id) { $link->setProps(array_merge($link->getProps(), ['id' => $id])); } $link->setRoute($metadata->getRoute(), $params, $metadata->getRouteOptions()); return $link; }
/** * @group 97 */ public function testLocationHeaderGeneratedDuringCreateContainsOnlyLinkHref() { $self = new Link('self'); $self->setUrl('http://localhost.localdomain/resource/foo'); $self->setProps(['vary' => 'true']); $entity = new HalEntity(['id' => 'foo', 'bar' => 'baz'], 'foo'); $links = $entity->getLinks(); $links->add($self, true); $this->resource->getEventManager()->attach('create', function ($e) use($entity) { return $entity; }); $result = $this->controller->create([]); $this->assertSame($entity, $result); $response = $this->controller->getResponse(); $headers = $response->getHeaders(); $this->assertTrue($headers->has('Location')); $this->assertNotContains('true', $headers->get('Location')->getFieldValue()); }