Skip to content

Commit

Permalink
Add support for custom attributes (close graphp#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrokeil committed Aug 28, 2019
1 parent a55994b commit d05e01f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@

class Loader
{
/**
* @var array
**/
private $attributeNamespaces;

public function __construct(array $attributeNamespaces = array())
{
$this->attributeNamespaces = $attributeNamespaces;
}

/**
* Loads a graph instance from the given GraphML contents.
*
Expand Down Expand Up @@ -111,6 +121,12 @@ private function loadAttributes(SimpleXMLElement $xml, AttributeAware $target, a
$key = $keys[(string)$dataElem['key']];
$target->setAttribute($key['name'], $this->castAttribute((string)$dataElem, $key['type']));
}

foreach ($this->attributeNamespaces as $attributeNamespace => $isPrefix) {
foreach ($xml->attributes($attributeNamespace, $isPrefix) as $attribute => $attributeValue) {
$target->setAttribute($attribute, $this->castAttribute((string) $attributeValue, ''));
}
}
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/LoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,32 @@ public function testAttributeDefault()
$this->assertEquals('n0', $vertex->getId());
$this->assertEquals('yellow', $vertex->getAttribute('color'));
}

public function testCustomAttributes()
{
$data = <<<EOL
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
graphml+xlink.xsd">
<graph edgedefault="directed">
<node id="n0" xlink:href="http://graphml.graphdrawing.org"/>
<node id="n1" />
<edge source="n0" target="n1" xlink:href="http://graphdrawing.org"/>
</graph>
</graphml>
EOL;
$this->loader = new Loader(array('xlink' => true));
$graph = $this->loader->loadContents($data);

$vertex = $graph->getVertices()->getVertexFirst();

$this->assertEquals('n0', $vertex->getId());
$this->assertEquals('http://graphml.graphdrawing.org', $vertex->getAttribute('href'));

$edge = $graph->getEdges()->getEdgeFirst();
$this->assertEquals('http://graphdrawing.org', $edge->getAttribute('href'));
}
}

0 comments on commit d05e01f

Please sign in to comment.