Skip to content
This repository has been archived by the owner on Aug 5, 2020. It is now read-only.

Commit

Permalink
CommonNamespaces: fixed shortenUri; added basic tests
Browse files Browse the repository at this point in the history
* shortenUri uses the first prefix it found and not the one with
longest URI. without the fix, results like happen: foo:bar/baz
* added tests for shortenUri and extendUri
  • Loading branch information
k00ni committed May 11, 2017
1 parent 6678152 commit 736d04a
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
27 changes: 26 additions & 1 deletion CommonNamespaces.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,39 @@ public function isShortenedUri($string)
return false == strpos($string, '://');
}

/**
* @param string $uri
* @return string
*/
public function shortenUri($uri)
{
$longestNamespaceInfo = null;

foreach ($this->namespaces as $ns => $nsUri) {
// prefix found
if (false !== strpos($uri, $nsUri)) {
return str_replace($nsUri, $ns .':', $uri);
if (null == $longestNamespaceInfo) {
$longestNamespaceInfo = array(
'ns' => $ns,
'nsUri' => $nsUri
);
continue;
}

if (strlen($nsUri) > strlen($longestNamespaceInfo['nsUri'])) {
$longestNamespaceInfo = array(
'ns' => $ns,
'nsUri' => $nsUri
);
}
}
}

// prefer the prefix with the longest URI to avoid results like foo:bar/fff
if (null !== $longestNamespaceInfo) {
return str_replace($longestNamespaceInfo['nsUri'], $longestNamespaceInfo['ns'] .':', $uri);
}

return $uri;
}
}
56 changes: 56 additions & 0 deletions Test/CommonNamespacesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Saft\Rdf\Test;

use Saft\Rdf\CommonNamespaces;
use Saft\Test\TestCase;

class CommonNamespacesTest extends TestCase
{
public function setUp()
{
parent::setUp();

$this->fixture = new CommonNamespaces();
}

/*
* Tests for extendUri
*/

public function testExtendUri()
{
$this->fixture->add('foo', 'http://foo/');

$this->assertEquals('http://foo/bar', $this->fixture->extendUri('foo:bar'));
}

public function testExtendUriOverlappingPrefixes()
{
$this->fixture->add('foo', 'http://foo/');
$this->fixture->add('foo2', 'http://foo/baz/');

$this->assertEquals('http://foo/baz/bar', $this->fixture->extendUri('foo2:bar'));
}

/*
* Tests for shortenUri
*/

public function testShortenUri()
{
$this->fixture->add('foo', 'http://foo/');

$this->assertEquals('foo:bar', $this->fixture->shortenUri('http://foo/bar'));
}

// test that in case you have overlapping namespace URIs, the longest will be used
// to avoid results like foo:bar/baz
public function testShortenUriOverlappingPrefixes()
{
$this->fixture->add('foo', 'http://foo/');
$this->fixture->add('foo2', 'http://foo/baz/');

$this->assertEquals('foo2:bar', $this->fixture->shortenUri('http://foo/baz/bar'));
}
}

0 comments on commit 736d04a

Please sign in to comment.