Permalink
Browse files

Allow empty self link

  • Loading branch information...
1 parent f51e2c7 commit 642a0908eafb1ed6ee4aa258ae3d97d12816d578 @baldurrensch baldurrensch committed Jan 8, 2013
Showing with 57 additions and 6 deletions.
  1. +6 −1 library/Hal/Link.php
  2. +7 −3 library/Hal/Resource.php
  3. +44 −2 tests/library/Hal/ResourceTest.php
View
7 library/Hal/Link.php
@@ -205,7 +205,12 @@ public function setTemplated($templated)
*/
public function toArray()
{
- $link = array('href' => $this->getHref());
+ $href = $this->getHref();
+ if (empty($href)) {
+ return array();
+ }
+
+ $link = array('href' => $href);
if($this->getTitle()){
$link['title'] = $this->getTitle();
}
View
10 library/Hal/Resource.php
@@ -104,7 +104,7 @@ public function setLink(Link $link, $singular=false, $plural=false)
/**
* Convenience function to set multiple links at once
- *
+ *
* @see Resource::setLink()
* @param array $links Array of Link objects
* @param boolean $singular
@@ -155,7 +155,11 @@ public function toArray()
{
$data = array();
foreach ($this->_links as $rel => $link) {
- $data['_links'][$rel] = $this->_recurseLinks($link);
+ $links = $this->_recurseLinks($link);
+
+ if (!empty($links)) {
+ $data['_links'][$rel] = $links;
+ }
}
foreach ($this->_data as $key => $value) {
$data[$key] = $value;
@@ -172,7 +176,7 @@ public function toArray()
protected function _recurseEmbedded($embeded)
{
$result = array();
- if($embeded instanceof self){
+ if($embeded instanceof self){
$result = $embeded->toArray();
} else {
foreach ($embeded as $embed) {
View
46 tests/library/Hal/ResourceTest.php
@@ -323,11 +323,53 @@ public function testEmptyResource()
$parent = new Resource('/dogs');
$parent->setLink(new Link('/dogs?q={text}', 'search'));
-
+
$parent->setEmbedded('dog', null);
-
+
$this->assertEquals(
json_decode($fixture), json_decode((string)$parent)
);
}
+
+ /**
+ * This tests adding a resource with no self link
+ */
+ public function testEmptySelfLink()
+ {
+ $fixture = <<<'EOF'
+{
+ "data": "value"
+}
+EOF;
+
+ $parent = new Resource('', array('data' => 'value'));
+
+ $this->assertEquals(
+ json_decode($fixture), json_decode((string) $parent)
+ );
+ }
+
+ /**
+ * This tests adding a resource with no self link
+ */
+ public function testEmptySelfLinkWithOthers()
+ {
+ $fixture = <<<'EOF'
+{
+ "_links":{
+ "search":{
+ "href":"/dogs?q={text}"
+ }
+ },
+ "data": "value"
+}
+EOF;
+
+ $parent = new Resource('', array('data' => 'value'));
+ $parent->setLink(new Link('/dogs?q={text}', 'search'));
+
+ $this->assertEquals(
+ json_decode($fixture), json_decode((string) $parent)
+ );
+ }
}

0 comments on commit 642a090

Please sign in to comment.